In this post, I would like to show you how to binding data to checkboxlist from database in asp.net. To do this , I need to binding data into checkboxlist control on page load.My database design in MS SQL Server 2008 , and I want to load data from column "country" in a table , tblcountry, into my checkboxlist when page is loading.
Sample table:
Figure 1: Sample table |
In ASP.Net:
Code Design:
<asp:CheckBoxList ID="CheckBoxList1" runat="server"></asp:CheckBoxList>
Code behind:
//import these two namespaces :System.Data and System.Data.SqlClient to use .NET
//Framework Data Provider for SQL Server
using System.Data;
using System.Data.SqlClient;
//Event page load
protectedvoidPage_Load(object sender, EventArgs e)
{
if (!IsPostBack) {
DataTable dt = new DataTable();
dt = Loadlist();
CheckBoxList1.DataSource = dt;
CheckBoxList1.DataValueField = "country";
//country is table field name in tblcountry
//country is table field name in tblcountry
CheckBoxList1.DataBind();
}
}
public DataTable Loadlist()
{
SqlConnection con = new SqlConnection();
string str;
string sql;
str="Server=UBEE_THAROTH;Database=Drink;uid=sa;pwd=123;";
sql = "Select * from tblcountry order by country asc";
con.ConnectionString = str;
con.Open();
SqlDataAdapter da = new SqlDataAdapter(sql,con);
DataTable dt = new DataTable();
da.Fill(dt);
if(dt.Rows.Count>0){
return dt;
}else {
return null;
}
}
SqlConnection con = new SqlConnection();
str="Server=UBEE_THAROTH;Database=Drink;uid=sa;pwd=123;";
sql = "Select * from tblcountry order by country asc";
con.ConnectionString = str;
con.Open();
SqlDataAdapter da = new SqlDataAdapter(sql,con);
if(dt.Rows.Count>0){
}
Result:
Figure 2: Checkboxlist |
Done.... :) :)
How to create dynamic Checkboxlist in asp.net using c#
Reviewed by BeiLover
on
6:44 PM
Rating:
No comments: