You can use two types of ASP.net controls to add a check box to a Web forms page: A separate CheckBox control or a CheckBoxList control. Both controls provide a way for the user to enter Boolean data (TRUE or FALSE, yes or no).
This article mainly introduces CheckBoxList, it goes without saying, see list to know is a list (collection), a control can contain multiple checkbox, below let us see the specific usage.
1. Binding Data
Copy Code code as follows:
This.lngCatalogID.DataSource = DT; Here I am tied to a DataTable.
This.lngCatalogID.DataTextField = "strCatalogName"; The value that the foreground sees, which is the value displayed in the CheckBoxList
This.lngCatalogID.DataValueField = "Lngcatalogid"; This value is not visible directly on the page, but in the source code you can see
This.lngCatalogID.DataBind ();
2. Get the selected item
Copy Code code as follows:
foreach (ListItem li in Lngcatalogid.items)
{
if (li. Selected)//indicates that an item has been selected
{
Li. Test indicates the value seen, corresponding to the strcatalogname above
Li. Value represents the values corresponding to the values you see. corresponding to the Lngcatalogid
}
}
3. Set an item as a hook-and-choose state
Copy Code code as follows:
foreach (ListItem li in Lngcatalogid.items)
{
if (li. Value.equals ("Hook selection")//if Li. Value is equal to a value, tick
{
Li. Selected = true; Equal to true means that the hook is selected.
Break
}
}
Select All in 4.DataGrid
Copy Code code as follows:
foreach (DataGridItem thisitem in Datagridlogininfo.items)
{
(CheckBox) thisitem.cells[0]. CONTROLS[1]). Checked = checkbox2.checked;
}
5. Reverse Selection
Copy Code code as follows:
for (int i = 0; i < CheckedListBox1.Items.Count; i++)
{
if (checkedlistbox1.getitemchecked (i))
{
Checkedlistbox1.setitemchecked (I, false);
}
Else
{
Checkedlistbox1.setitemchecked (I, true);
}
}
CheckBoxList Control Usage Examples
Example one, looping through each option, contains the corresponding value set to the selected state
Copy Code code as follows:
for (int i = 0; i < hfAnswers.Value.Split (', '). Length; i++)//Assign value to CheckBoxList selected check box
{
for (int j = 0; J < CBoxListAnswer.Items.Count; J + +)
{
if (HfAnswers.Value.Split (', ') [i] = = Cboxlistanswer.items[j]. Value)
{
CBOXLISTANSWER.ITEMS[J]. Selected = true;
}
}
}
Example two, loop to traverse read each option, the value of the selected option is spliced into a string for subsequent insertion into the database
Copy Code code as follows:
String m_strtemp = String. Empty;
for (int i = 0; i < CBoxListAnswer.Items.Count; i++)//Read CheckBoxList selected value, save it
{
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;