可以使用兩種類型的 ASP.NET 控件將復(fù)選框添加到 Web 窗體頁上:單獨(dú)的 CheckBox 控件或 CheckBoxList 控件。兩種控件都為用戶提供了一種輸入布爾型數(shù)據(jù)(真或假、是或否)的方法。
本文主要介紹CheckBoxList,不言而喻,看到List就知道是一個(gè)列表(集合),一個(gè)控件可以包含多個(gè)CheckBox,下面讓我們來看看具體的用法。
1.綁定數(shù)據(jù)
代碼如下:
this.lngCatalogID.DataSource = dt; //這里我綁到DataTable上了.
this.lngCatalogID.DataTextField = "strCatalogName"; //前臺看到的值,也就是CheckBoxList中顯示出來的值
this.lngCatalogID.DataValueField = "lngCatalogID"; //這個(gè)值直接在頁面上是看不到的,但在源代碼中可以看到
this.lngCatalogID.DataBind();
2.獲取鉤選的項(xiàng)
代碼如下:
foreach(ListItem li in lngCatalogID.Items)
{
if(li.Selected) //表示某一項(xiàng)被選中了
{
//li.Test表示看到的值,對應(yīng)上面的strCatalogName
//li.Value表示看到的值對應(yīng)的值.對應(yīng)上面的lngCatalogID
}
}
3.設(shè)置某項(xiàng)為鉤選狀態(tài)
代碼如下:
foreach(ListItem li in lngCatalogID.Items)
{
if(li.Value.Equals("鉤選條件")) //如果li.Value值等于某值,就鉤選
{
li.Selected = true; //等于true就表示鉤選啦.
break;
}
}
4.DataGrid中全選
代碼如下:
foreach(DataGridItem thisItem in DataGridLogininfo.Items)
{
((CheckBox)thisItem.Cells[0].Controls[1]).Checked = CheckBox2.Checked;
}
5.反向選擇
代碼如下:
for (int i = 0; i < checkedListBox1.Items.Count; i++)
{
if (checkedListBox1.GetItemChecked(i))
{
checkedListBox1.SetItemChecked(i, false);
}
else
{
checkedListBox1.SetItemChecked(i, true);
}
}
CheckBoxList控件用法范例
范例一、循環(huán)遍歷每個(gè)選項(xiàng),包含的對應(yīng)值的設(shè)置為選中狀態(tài)
代碼如下:
for (int i = 0; i < hfAnswers.Value.Split(',').Length; i++)//給CheckBoxList選中的復(fù)選框 賦值
{
for (int j = 0; j < CBoxListAnswer.Items.Count; j++)
{
if (hfAnswers.Value.Split(',')[i] == CBoxListAnswer.Items[j].Value)
新聞熱點(diǎn)
疑難解答
圖片精選