Thursday, 1 August 2013

How to bind CheckBoxList in Asp.Net with SqlServer


How to  bind  CheckBoxList in Asp.Net with SqlServer


//Execute this query in Sql Server ………………………………..

create  database test
create table CityName(SrNo int  identity(1,1) primary key,Name nvarchar(50))
insert into CityName('Noida')
insert into CityName('Ballia')
insert into CityName('Delhi')
insert into CityName('Varanasi')


//Code for Default.aspx.cs ………………………………..

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<table width="50%">
<tr><td colspan="2"><b><i><font color="green">CheckBoxList Bind with Sql Server </font></i> </b></td></tr>
<tr><td><b><font color="Red">City Name</font></b></td><td>

<asp:CheckBoxList ID="CheckBoxList1" runat="server" AutoPostBack="True"
onselectedindexchanged="CheckBoxList1_SelectedIndexChanged"
RepeatDirection="Horizontal">
</asp:CheckBoxList>
</td></tr>
<tr><td>Text Field </td><td>
<asp:Label ID="lblcityname" runat="server"></asp:Label>
</td></tr>
<tr><td>Value Field</td><td><asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
</td></tr>
</table>

<br />

</div>
</form>
</body>
</html>

//Code for Default.cs ………………………………..

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
checkboxlistbind();
}
}

string city="  ";
string sn="  ";
private void checkboxlistbind()
{
SqlConnection con = new SqlConnection(@"Data Source=KUSH-PC\KUSH;Initial Catalog=test;Integrated Security=True");
SqlCommand cmd = new SqlCommand("select SrNo,Name from CityName", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
CheckBoxList1.DataSource = dt;
CheckBoxList1.DataTextField = "Name";
CheckBoxList1.DataValueField = "SrNo";
CheckBoxList1.DataBind();
}
protected void CheckBoxList1_SelectedIndexChanged(object sender, EventArgs e)
{

foreach (ListItem li in CheckBoxList1.Items)
{
if (li.Selected)
{
sn += li.Value + ",";
city += li.Text.ToString() + ",";


}
}

TextBox1.Text = sn.Remove(sn.Length - 1);
lblcityname.Text = city.Remove(city.Length-1);
}
}






1 comments: