Bind data to checkbox list from database in C# (Fiil Checkbox list from table in asp.net c#)

In this blog i am going to explain how to dynamically Bind/Load/Fill CheckBoxList with the data from the Sql Server table.


  • First of all n the design page(.aspx) place a CheckBoxList control as:


         <asp:CheckBoxList ID="ckQualification" runat="server" RepeatColumns="2">
        </asp:CheckBoxList>


  • Now Create a connectionstring in the web.config file under configuration tag as:

<configuration>
<connectionStrings>
                                <add name="Conn" connectionString="Data Source=.;Initial Catalog=My_DB;Integrated Security=True"/>
</connectionStrings>
</configuration>



  • Now, Create a Database "My_DB" in sql server and also create a table "Qualifications" having 2 fields : 

         "Qualification_Id int identity(1,1) primary key not null, Qualification varchar(50)"

Note: Don't forgot to enter few data eg. MCA, Engg., BE, etc...;)



  • 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)
        {      
            FillQualificationCheckBoxList();
        }
    }

private void FillQualificationCheckBoxList()
    {
        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Conn"].ConnectionString);
        SqlCommand cmd = new SqlCommand("Select * from My_DB", con);
        SqlDataAdapter adp = new SqlDataAdapter(cmd);
        DataTable dt = new DataTable();
        adp.Fill(dt);
        ckQualification.DataSource = dt;
        ckQualification.DataTextField = "Qualification";
        ckQualification.DataValueField = "Qualification_Id";
        ckQualification.DataBind();    
    } 

Comments

Popular posts from this blog

How to show enlarge image when mouse hover on image or link in Asp.Net(c#) using JavaScript

StateCode and StatusCode Values for mostly used entities in Microsoft Dynamics CRM 2013

Search data in Gridview on Textbox Key press event using JQuery in Asp.Net- C#

go to top image