根据字符串中的字符选择复选框列表项

时间:2016-05-25 12:46:41

标签: c# asp.net

我有一个字符串变量如下

string s = "QQQNQQQ";

我还有一个包含以下项目的CheckboxList

<asp:CheckBoxList ID="cbWorkPattern" runat="server" AutoPostBack="true" RepeatDirection="Horizontal" OnSelectedIndexChanged="cbWorkPattern_SelectedIndexChanged">
    <asp:ListItem Text="Sunday" Value="0"></asp:ListItem>
    <asp:ListItem Text="Monday" Value="1" ></asp:ListItem>
    <asp:ListItem Text="Tuesday" Value="2" ></asp:ListItem>
    <asp:ListItem Text="Wednesday" Value="3" ></asp:ListItem>
    <asp:ListItem Text="Thursday" Value="4" ></asp:ListItem>
    <asp:ListItem Text="Friday" Value="5" ></asp:ListItem>
    <asp:ListItem Text="Saturday" Value="6"></asp:ListItem>
</asp:CheckBoxList>

当字符串s中的字符等于“Q”时,我想在CheckBoxList中选择每个CheckBox。例如,在上面给定的字符串中,应取消选择星期三,并选择剩余的天数。我怎样才能用c#实现这个目标?

1 个答案:

答案 0 :(得分:1)

如果你知道你将总是有七个字符,你可以遍历你的字符串,并使用包含&#34; Q&#34;的索引从CheckBoxList中选择项目。 :

string s = "QQQNQQQ";
// Iterate through your string
for(var i = 0; i < s.Length; i++)
{
     // If the current character is 'Q', then select this option
     if(s[i] == 'Q')
     {
          // Find the cooresponding value for this element and select it
          cbWorkPattern.Items.FindByValue(i.ToString()).Selected = true;
     }
}

会产生:

enter image description here

相关问题