2017-04-14 189 views
1

我收到了几个复选框,但我只希望文本“新桌面”和“新笔记本电脑”只能选择2个。我希望它可以在C#中完成。从2中选择1复选框

<asp:CheckBoxList ID="Service1" runat="server" 
        Width="251px" > 
       <%--onselectedindexchanged="checkBox1_CheckedChanged"--%> 
        <asp:ListItem text="New Login ID & Email Address" ></asp:ListItem> 
        <asp:ListItem text="New Desktop" Value="2" oncheckedchanged="checkBox1_CheckedChanged" ></asp:ListItem> 
        <asp:ListItem text="New Notebook" Value="3" oncheckedchanged="checkBox2_CheckedChanged"></asp:ListItem> 
        <asp:ListItem text="New Mouse"></asp:ListItem> 
        <asp:ListItem text="New Keyboard"></asp:ListItem> 
        <asp:ListItem text="New Printer"></asp:ListItem> 
       </asp:CheckBoxList> 


//.cs pages 
protected void checkBox1_CheckedChanged(object sender, EventArgs e) 
     { 
      if (Service1.Items[2].Selected == true) 
      { 
       Service1.Items[3].Enabled = false; 
      } 
     } 
protected void checkBox2_CheckedChanged(object sender, EventArgs e) 
     { 
      if (Service1.Items[3].Selected == true) 
      { 
       Service1.Items[2].Enabled = false; 
      } 
     } 
+0

这也许能帮助 - http://stackoverflow.com/a/10553349/6538824 –

+0

谢谢Giorgi的,因为我还是一个初学者我真的不明白写的方式。 – Johnny

+0

你上面给出的代码不工作? –

回答

1

我在下面给你一个例子,但这仍然不是一个可行的方法。你需要的CheckedChanged事件添加到每个复选框从其他复选框

protected void CheckBox1_CheckedChanged(object sender, EventArgs e) 
{ 
    if(CheckBox1.Checked) 
    { 
      CheckBox2.Checked =false; 
      CheckBox3.Checked =false; 
      CheckBox4.Checked =false; 
     } 
} 

删除检查你应该重复上述evevt为CheckBox2,CheckBox3等。您可以根据您的要求扩展它。

但在这种情况下,我会建议您使用ASP.NET单选按钮控件。有关单选按钮控件的更多信息,请参阅this link

1

可以使用OnSelectedIndexChanged事件的CheckBoxList用的AutoPostBack =“真”,让您控制发送请求到服务器,并选择chenged活动将调用 即:对于设计

<asp:CheckBoxList ID="Service1" runat="server" Width="251px" AutoPostBack="True" OnSelectedIndexChanged="Service1_SelectedIndexChanged"> 
     <asp:ListItem Text="New Login ID & Email Address"></asp:ListItem> 
     <asp:ListItem Text="New Desktop" Value="2"></asp:ListItem> 
     <asp:ListItem Text="New Notebook" Value="3" ></asp:ListItem> 
     <asp:ListItem Text="New Mouse"></asp:ListItem> 
     <asp:ListItem Text="New Keyboard"></asp:ListItem> 
     <asp:ListItem Text="New Printer"></asp:ListItem> 
    </asp:CheckBoxList> 

,并在代码:“礼”有所有选择的项目,并根据您的要求“新桌面”和“新笔记本电脑”只能选择2分之一。

protected void Service1_SelectedIndexChanged(object sender, EventArgs e) 
     { 
      CheckBoxList li = (CheckBoxList)sender; 
      foreach (ListItem l in li.Items) 
      { 
       if (l.Value == "2") 
       { 
        if (l.Selected) 
        { 
         Service1.Items[2].Enabled = false; 
        } 
        else 
        { 
         Service1.Items[2].Enabled = true; 
        } 

       } 
       else if (l.Value == "3") 
       { 
        if (l.Selected) 
        { 
         Service1.Items[1].Enabled = false; 
        } 
        else 
        { 
         Service1.Items[1].Enabled = true; 
        } 
       } 
      } 
     }