Wednesday, 5 June 2013

How to Fill CheckBoxList from Sql Server table in

How to Fill CheckBoxList from Sql Server table in

ntroduction: In one of my previous article i  explained  Fill CheckBoxList based on DropDownList selection in, VB)  and How to get CheckBoxList selected items in comma separated format in,VB)  and How to validate CheckBoxList using JavaScript in, VB) and  How to fill DropDownList from Sql server database in    Now in this article I am going to explain how to dynamically fill CheckBoxListwith the data from the Sql Server table. It  is one of very common requirement while working on application.
checkboxlist example in
  • In the design page(.aspx) place a DropDownList and a CheckBoxList control as:
         <asp:CheckBoxList ID="cblCourses" runat="server" RepeatColumns="2">
  • Create a connectionstring in the web.config file under configuration tag as:
                                <add name="MyDbCon" connectionString="Data Source=LALIT;Initial Catalog=MyDataBase;Integrated Security=True"/>
  •  Create a table in sql server and name it  Qualification_Tb:

  • Now in the code behind file(.aspx.cs) write the code as


using System.Data;
using System.Data.SqlClient;
using System.Configuration;
protected void Page_Load(object sender, EventArgs e)
if (!Page.IsPostBack)

private void FillQualCheckBoxList()
        SqlConnection con = newSqlConnection(ConfigurationManager.ConnectionStrings["MyDbCon"].ConnectionString);
        SqlCommand cmd = new SqlCommand("Select * from Qualification_Tb", con);
        SqlDataAdapter adp = new SqlDataAdapter(cmd);
        DataTable dt = new DataTable();
        cblCourses.DataSource = dt;
        cblCourses.DataTextField = "Qualification";
        cblCourses.DataValueField = "Qualification_Id_Pk";

1 comment: