2017-04-14 192 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; 
        } 
       } 
      } 
     }