In this article, we are going to learn how to Bind Checkboxlist Control from DataTable(DataSet) c-sharp code in asp.net
In designer file:
In Designer File, create a Checkboxlist Control named as chblstCity.
div align="center">
CheckBoxList ID="chblstCity" runat="server">CheckBoxList>
div>
Namespaces used:
Include the below Namespace.
using System.Data;
Complete Code:
Here, we are creating a Datatable dt and adding two columns named as CityId(Int) and CityName(string). Added rows to DataTable and assiging to text Field and value field of CheckBoxList
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindCheckBoxList();
}
}
public void BindCheckBoxList()
{
//Creating DataTable
DataTable dt = new DataTable();
//adding Columns to DataTable
dt.Columns.Add("CityId", typeof(Int32));
dt.Columns.Add("CityName", typeof(string));
//Addding data to DataTable
dt.Rows.Add(1, "Delhi");
dt.Rows.Add(2, "Mumbai");
dt.Rows.Add(3, "Chennai");
dt.Rows.Add(4, "Kolkata");
chblstCity.DataSource = dt;
chblstCity.DataTextField = "CityName";
//Assigining Text Field
chblstCity.DataValueField = "CityId";
//Assigining Value Field
chblstCity.DataBind();
}
Output:
Output will be shown as below.