Tuesday 16 June 2015

How to bind CheckBoxList from database

Here I will explain how to bind CheckBoxList from database
and in previous I posted this articles

How to bind DropdownList from database
how to access asp.net website in LAN
how to create database from script file

Checkboxlist is group of checkbox. You can check multiple item in CheckBoxList control in asp.net.
If item list is too more than use the DropDownList .

If you want to bind CheckBoxList from database table then you write following code in your website.
First , Your .aspx page should be like this

<%@ 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> How to bind CheckBoxList from database </title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:CheckBoxList ID="chkType" runat="server">
            </asp:CheckBoxList>
      
    </div>
    </form>
</body>
</html>



And your code behind like this

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

using System.Data;
using System.Data.SqlClient;
using System.Configuration;

public partial class _Default : System.Web.UI.Page
{
    SqlConnection cn;
    DataTable dt;
    protected void Page_Load(object sender, EventArgs e)
    {
        cn = new SqlConnection(ConfigurationManager.ConnectionStrings["Conn"].ConnectionString);
        if (!IsPostBack)
        {
            BindCheckBoxList();
        }

    }
    public void BindCheckBoxList()
    {
        SqlCommand cmd = new SqlCommand("SELECT id,Name from tbl",cn);
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        dt = new DataTable();
        da.Fill(dt);

        chkType.DataSource = dt;
        chkType.DataTextField = "Name";
        chkType.DataValueField = "Id";
        chkType.DataBind();
    }
}




No comments:

Post a Comment



Asp.net tutorials