asp.net c# examples code for web developers.

DataBind CheckBoxList with array in asp.net c#

DataBind a CheckBoxList with array
The following asp.net c# example code demonstrate us how can we data bind a CheckBoxList web server control programmatically at run time with an Array data source object. CheckBoxList is an asp.net list web server control. CheckBoxList allow web users to select/check one or more items at a time.

CheckBoxList contain ListItem objects. Each ListItem object represent an item. We can populate a CheckBoxList from Array elements. To do this, first we need to initialize an array object. Then we populate the Array with items (elements). Next, we need to specify the newly created Array as CheckBoxList control's DataSource. Finally, we can data bind CheckBoxList control with Array by calling the CheckBoxList DataBind() method.

The populated CheckBoxlist's create the same number of items as the number of elements exists in Array. Each Array element create an item in CheckBoxList. We populated CheckBoxList from a one dimensional String Array, so the CheckBoxList item 'Text' and 'Value' property carry the same value.
StringArrayCheckBoxList.aspx

<%@ Page Language="C#" %>

<!DOCTYPE html>

<script runat="server">

    protected void Button1_Click(object sender, System.EventArgs e)
    {
        string[] controlArray = { "Localize", "Label", "Panel", "ListBox", "RadioButton" };
        Label1.Text = "String array created and bind with CheckBoxList successfully!";
        CheckBoxList1.DataSource = controlArray;
        CheckBoxList1.DataBind();
    }
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>How to populate (DataBind) CheckBoxList using string array DataSource in asp.net</title>
</head> 
<body>
    <form id="form1" runat="server">
    <div>
        <h2 style="color:Green">asp.net array example: String Array and CheckBoxList</h2>
        <asp:Label 
             ID="Label1" 
             runat="server" 
             Font-Size="Large"
             ForeColor="SaddleBrown"
             Font-Bold="true"
             Font-Italic="true"
             >
        </asp:Label>
        <br /><br />
        <asp:CheckBoxList 
             ID="CheckBoxList1" 
             runat="server" 
             BackColor="SteelBlue" 
             ForeColor="FloralWhite"
             >
        </asp:CheckBoxList>
        <br /><br />
        <asp:Button 
             ID="Button1" 
             runat="server" 
             OnClick="Button1_Click"
             Font-Bold="true"
             Text="Populate CheckBoxList With String Array"
             ForeColor="SaddleBrown"
             />   
    </div>
    </form>
</body>
</html>
More asp.net examples
Copyright © 2008-2015 | asp.net c# examples | asp-net-example.blogspot.com | Author Saiful Alam