Detailed usage of CheckBoxList check box list control in ASP. NET
- 2021-07-13 05:06:23
- OfStack
You can use two types of ASP. NET controls to add check boxes to an Web form page: a separate CheckBox control or an CheckBoxList control. Both controls provide a way for users to enter Boolean data (true or false, yes or no).
This article mainly introduces CheckBoxList. It goes without saying that List is a list (collection), and a control can contain multiple CheckBox. Let's take a look at the specific usage below.
1. Bind data
this.lngCatalogID.DataSource = dt; // Here I'm tied to DataTable Here we go .
this.lngCatalogID.DataTextField = "strCatalogName"; // The value seen by the foreground , That is CheckBoxList The value displayed in the
this.lngCatalogID.DataValueField = "lngCatalogID"; // This value is not visible directly on the page , But you can see it in the source code
this.lngCatalogID.DataBind();
2. Get the checked item
foreach(ListItem li in lngCatalogID.Items)
{
if(li.Selected) // Indicates a 1 Item is selected
{
//li.Test Indicates the value seen , Corresponding to the above strCatalogName
//li.Value Represents the value corresponding to the value seen . Corresponding to the above lngCatalogID
}
}
3. Set an item to be checked
foreach(ListItem li in lngCatalogID.Items)
{
if(li.Value.Equals(" Hook condition ")) // If li.Value Value is equal to a value , Just tick
{
li.Selected = true; // Equal to true It means it is checked .
break;
}
}
4. All selections in DataGrid
foreach(DataGridItem thisItem in DataGridLogininfo.Items)
{
((CheckBox)thisItem.Cells[0].Controls[1]).Checked = CheckBox2.Checked;
}
Step 5 Reverse selection
for (int i = 0; i < checkedListBox1.Items.Count; i++)
{
if (checkedListBox1.GetItemChecked(i))
{
checkedListBox1.SetItemChecked(i, false);
}
else
{
checkedListBox1.SetItemChecked(i, true);
}
}
Example Usage of CheckBoxList Control
Example 1. Loop through each option, containing the setting of the corresponding value to the selected state
for (int i = 0; i < hfAnswers.Value.Split(',').Length; i++)// To CheckBoxList Selected check box Assignment
{
for (int j = 0; j < CBoxListAnswer.Items.Count; j++)
{
if (hfAnswers.Value.Split(',')[i] == CBoxListAnswer.Items[j].Value)
{
CBoxListAnswer.Items[j].Selected = true;
}
}
}
Example 2. Loop through each option, splicing the value of the selected option into a string for subsequent insertion into the database
string m_strTemp = string.Empty;
for (int i = 0; i < CBoxListAnswer.Items.Count; i++)// Read CheckBoxList Selected value , Preserve
{
if (CBoxListAnswer.Items[i].Selected)
{
m_strTemp += CBoxListAnswer.Items[i].Value + ",";
}
}
if (!string.IsNullOrEmpty(m_strTemp))
Label1.Text = m_strTemp.Substring(0, m_strTemp.Length - 1);
else
Label1.Text = m_strTemp;