【问题标题】:How to disable a checkbox if another checkbox is enabled?如果启用了另一个复选框,如何禁用一个复选框?
【发布时间】:2019-08-13 02:24:39
【问题描述】:

我的网页有两个复选框,我想要的是:

  • 最初两个复选框都未选中。
  • 如果 Checkbox1 被选中,Checkbox2 应该被禁用。
  • 如果 Checkbox2 再次被取消选中,Checkbox2 应该会再次启用。
  • 反之亦然。

请帮我修改我的代码。

这是我的代码:

protected void CheckBox1_CheckedChanged1(object sender, EventArgs e)
{
   //this.CheckBox1.CheckedChanged += new System.EventHandler(CheckBox1_CheckedChanged1);
    if (CheckBox1.Checked)
        CheckBox2.Enabled = false;
}

protected void CheckBox2_CheckedChanged2(object sender, EventArgs e)
{
    if (CheckBox2.Checked)
        CheckBox1.Enabled = false;
}

HTML

<asp:CheckBox ID="CheckBox1" runat="server" Height="33px" OnCheckedChanged="CheckBox1_CheckedChanged1" Font-Bold="True" style="margin-left: 33px" Text="Remove Blank Lines" TextAlign="Left" Width="162px" />


<asp:CheckBox ID="CheckBox2" runat="server" Font-Bold="True" Height="33px" OnCheckedChanged="CheckBox2_CheckedChanged2" style="margin-left: 28px" Text="Add Prefix/ Suffix to Blank Lines" TextAlign="Left" Width="259px" />

【问题讨论】:

  • 为什么不只使用单选按钮?

标签: c# html checkbox webforms


【解决方案1】:

只需使用:

CheckBox2.Enabled = !CheckBox1.Checked;

【讨论】:

  • @Emmy,我认为您必须在 CheckBox2_CheckedChanged2 事件处理程序中为 CheckBox1 写上上述条件,也像 => CheckBox1.Enabled = !CheckBox2.Checked;
  • 可能@Emmy 假定这是客户端代码,而实际上它是需要AutoPostBack="true" 或提交按钮的服务器端代码。也许也提供一个仅限客户端的解决方案?
【解决方案2】:

这个答案是为了澄清新的贡献者

AutoPostBack 属性添加到每个复选框控件

<asp:CheckBox ID="CheckBox1" runat="server" AutoPostBack ="True" OnCheckedChanged="CheckBox_CheckedChanged" Height="33px"  Font-Bold="True" style="margin-left: 33px"  Text="Remove Blank Lines" TextAlign="Left" Width="162px" />


<asp:CheckBox ID="CheckBox2" runat="server" AutoPostBack ="True" OnCheckedChanged="CheckBox_CheckedChanged" Font-Bold="True" Height="33px"  style="margin-left: 28px"   Text="Add Prefix/ Suffix to Blank Lines" TextAlign="Left" Width="259px" />

然后在代码隐藏中

创建一个事件CheckBox_CheckedChanged 并将每个checkbox 指向它:

protected void CheckBox_CheckedChanged(object sender, EventArgs e)
  {
     CheckBox1.Enabled = !CheckBox2.Checked;
     CheckBox2.Enabled = !CheckBox1.Checked;
  }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-08-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多