如何检查asp.net中checkboxlist上的特定项目

时间:2015-05-27 05:35:01

标签: c# asp.net webforms

这里是我用来检查字符串匹配项但不起作用的代码

foreach(ListItem li in Checklistbox1.Items)
{
    if(li.text == "John")
     {
         li.selected = true;
     }
}

请帮我解决这个问题

2 个答案:

答案 0 :(得分:5)

你可以不用循环尝试这样:

Checklistbox1.Items.FindByValue("John").Selected = true;

或者你可以试试这个:

foreach(ListItem li in Checklistbox1.Items)
{
    if(li.Value == "John")
     {
         li.selected = true;
     }
}

或者您可以尝试这样:

foreach (var item in Checklistbox1.Items.Cast<ListItem>()
        .Where (li => li.Value == "John"))
   item.Selected = true;

答案 1 :(得分:0)

没有循环:

void yourbutton_click(Object sender, EventArgs e)
{
    Checklistbox1.Items.FindByText("John").Selected = true;
}

使用foreach循环:

foreach(ListItem li in Checklistbox1.Items)
{
    if(li.Text == "John")
    {
        li.Selected = true;
    }
}

使用for循环:

for (int i = 0; i < Checklistbox1.Items.Count; i++)
{
     if(Checklistbox1.Items[i].Text == "John")
     {
          Checklistbox1.Items[i].Selected = true;
     }       
}
相关问题