Dynamic generation of a Check Box List



In this article we discus how to bind CheckBox with Database.

In Asp.Net we have two controls one is CheckBox and other is CheckBoxList. Here we discuss about CheckBoxList Control.

Using this control we are able to bind our data dynamically.

I am using a table name as "SkillsDetails".

Table Name: Skills

Create table Skills(SkillId int primary key,SkillName nvarchar(50))

[Note: copy the above statement and paste in MS-SQL server and run it; the table is created]

  • Open vs2008 and create new website
  • Open webpage1.aspx
  • Write the following code

    <asp:CheckBoxList ID="chkSkills" runat="server">

    </asp:CheckBoxList>
  • Now open webpage1.aspx.cs file and write the following code in the Page Load Event

    LoadSkills();

    private void LoadSkills()
    {
        
    try
        {
            
    DataTable dt = new Pigo.DBUtility.SqlHelper().GetDataTable("SELECT SkillID,' '+ SkillName as SkillName  from SkillDetails"null);
            
    if (dt != null)
            {
                chkSkills.DataValueField = 
    "SkillID";
                chkSkills.DataTextField = 
    "SkillName";
                chkSkills.DataSource = dt;
                chkSkills.DataBind();
            }
            dt = 
    null;
        }
        
    catch (Exception ex)
        { }
    }


[Note: In the above LoadSkills() you see Pigo.DBUtility.SqlHelper().GetDataTable(). Pigo.DBUtility is a namespace created by me and GetDataTable is a method that takes two parameters; one is String and the other isSqlParameter array; a DataTable is returned. In this method I my SQL query and the other parameter is null. If you are using this then please write your database connectivity code and use it.

chkSkills.DataValueField : In this field we assign our unique Id; in this example I assign "SkillsID" as the Primary key.

chkSkills.DataTextField : In this field we assign Text field; in this example I assign "SkillsName"

chkSkills.DataSource : It means from where I get data. According to this Example I assign dt that is a instance of DataTable Class and have some data based on my Sql Query.

chkSkills.DataBind(): Using this we tell the compiler to please bind this data for me.

DataTable dt = new Pigo.DBUtility.SqlHelper().GetDataTable("SELECT SkillID,' '+ SkillName as SkillName  from SkillDetails",null);
[NOTE: This is my database code; you place your database connection code; you write here your own database code … ]
Some function may help you

When we talk about CheckBox or CheckBoxList, the first thing that comes to mind is that it will be multiple selection.

The function below tells you how to make a string with multiple selected check box.
  1. Generate string using multiple select CheckBox.

    Public String MakeString(CheckBoxList chkSkills)
    {
       
    int[] Skills = new int[chkSkills.Items.Count];
       
    StringBuilder Skill = new StringBuilder();
       
    String delimeter = String.Empty;
        for (int i = 0; i < chkSkills.Items.Count; i++)
        {
           
    if (chkSkills.Items[i].Selected)
            {
                Skills[i] = 
    Convert.ToInt32((chkSkills.Items[i].Value).ToString());      Skill.Append(delimeter + chkSkills.Items[i].Text.ToString());
                delimeter = 
    ", ";
            }
        }
        String str = Skill.ToString();
       
    Return str;
    }


    [NOTE : In this Example ,(comma) is a separator, you can replace it according to your convince
     

  2. Generate a string array from a string with , (Comma) as the separator

    Public String[] GetArray(String str)
    {

       // Split() is a readyment function it ll split string based on char     // seprator
        String[] Keyword = str.Split(',');
        return Keyword;
    }
     
  3. CheckBoxList is Empty or not

    The following function returns the total number of selected CheckBox items.

    private int CheckboxEmpty(CheckBoxList chkSkills)
    {
       
    int selectCount = 0, unselectCount = 0;
       
    for (int i = 0; i < chkSkills.Items.Count; i++)
        {
           
    if (chkSkills.Items[i].Selected)
                selectCount++;
           
    else
               
    unselectCount++;
        }
       
    return selectCount;
    }