DataBind a CheckBoxList with array
The following ASP.NET C# example code demonstrates to 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 allows web users to select/check one or more items at a time.
CheckBoxList contains ListItem objects. Each ListItem object represents 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 creates the same number of items as the number of elements that exist in the Array. Each Array element creates an item in CheckBoxList. We populated CheckBoxList from a one-dimensional String Array, so the CheckBoxList item 'Text' and 'Value' properties carry the same value.
CheckBoxList contains ListItem objects. Each ListItem object represents 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 creates the same number of items as the number of elements that exist in the Array. Each Array element creates an item in CheckBoxList. We populated CheckBoxList from a one-dimensional String Array, so the CheckBoxList item 'Text' and 'Value' properties 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>