Wednesday 5 June 2013

How to Fill CheckBoxList from Sql Server table in asp.net

How to Fill CheckBoxList from Sql Server table in asp.net


ntroduction: In one of my previous article i  explained  Fill CheckBoxList based on DropDownList selection in asp.net(C#, VB)  and How to get CheckBoxList selected items in comma separated format in asp.net(C#,VB)  and How to validate CheckBoxList using JavaScript in Asp.net(C#, VB) and  How to fill DropDownList from Sql server database in asp.net    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 asp.net application.
 
checkboxlist example in asp.net
  • In the design page(.aspx) place a DropDownList and a CheckBoxList control as:
         <asp:CheckBoxList ID="cblCourses" runat="server" RepeatColumns="2">
        </asp:CheckBoxList
  • Create a connectionstring in the web.config file under configuration tag as:
<configuration>
<connectionStrings>
                                <add name="MyDbCon" connectionString="Data Source=LALIT;Initial Catalog=MyDataBase;Integrated Security=True"/>
</connectionStrings>
</configuration>
  •  Create a table in sql server and name it  Qualification_Tb:


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

 C#.NET

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

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();
        adp.Fill(dt);
        cblCourses.DataSource = dt;
        cblCourses.DataTextField = "Qualification";
        cblCourses.DataValueField = "Qualification_Id_Pk";
        cblCourses.DataBind();       
    }

1 comment:

  1. It is imperative that we read blog post very carefully. I am already done it and find that this post is really amazing.
    澳洲cs代写

    ReplyDelete