Introduction:
Now in this article I am going to explain how
to dynamically bind/Load/Fill CheckBoxList with the data from
the SQL Server table. It is one of very common
requirement while working on asp.net application.
- In the design page(.aspx) place a DropDownList and a
CheckBoxList control as:
<fieldset style="width:300px">
<legend>Fill CheckBoxList Dynamically</legend>
<asp:CheckBoxList ID="cblDept"
runat="server"
RepeatColumns="2">
</asp:CheckBoxList>
</fieldset>
<configuration>
<connectionStrings>
<add name="EmpCon" connectionString="Data Source=localHost;Initial
Catalog=test;Integrated Security=True"/>
</connectionStrings>
</configuration>
Create a Database e.g. "Test"
in sql server and also create a table as
shown below and name
it "Dept_table"
Now in the code behind file(.aspx.cs)
write the code as
Asp.Net C# Code to Bind/Load/Fill CheckBoxList from Sql
server Database in asp.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 = new
SqlConnection(ConfigurationManager.ConnectionStrings["EmpCon"].ConnectionString);
SqlCommand cmd = new
SqlCommand("Select
* from Dept_table", con);
SqlDataAdapter adp = new
SqlDataAdapter(cmd);
DataTable dt = new
DataTable();
adp.Fill(dt);
cblDept.DataSource = dt;
cblDept.DataTextField = "Dept_name";
cblDept.DataValueField = "Dept_Id_Pk";
cblDept.DataBind();
}
}
VB.Net Code to
Bind/Load/Fill CheckBoxList from Sql server Database in asp.net
Now in the code behind file(.aspx.vb) write the code as:
Imports System.Data
Imports System.Data.SqlClient
Imports System.Configuration
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not Page.IsPostBack Then
FillQualCheckBoxList()
End If
End Sub
Private Sub FillQualCheckBoxList()
Dim con As NewSqlConnection(ConfigurationManager.ConnectionStrings("EmpCon").ConnectionString)
Dim cmd As New SqlCommand("Select * from Dept_table", con)
Dim adp As New SqlDataAdapter(cmd)
Dim dt As New DataTable()
adp.Fill(dt)
cblCourses.DataSource = dt
cblCourses.DataTextField = "Dept_name"
cblCourses.DataValueField = "Dept_Id_Pk"
cblCourses.DataBind()
End Sub
0 comments:
Post a Comment