【问题标题】:webform that automatically checks button if another button is checked如果选中另一个按钮,则自动检查按钮的网络表单
【发布时间】:2012-08-24 11:02:13
【问题描述】:

我正在尝试在 asp.net/c# 中创建一个使用复选框的网络表单。如果选中另一个框,我想做的是自动选中一个框

例如如果button2被选中,则自动检查button1,但不自动检查button1是否被选中

尝试做一个 if 语句来处理这个问题:

if(checkbox1.changed == true)
{
    checkbox2.changed == true;
} 

但这没有用。任何人都指出我在哪里寻找如何做到这一点的正确方向。

【问题讨论】:

    标签: c# asp.net checkbox webforms


    【解决方案1】:

    你的意思是这样的?

    default.aspx

    <form id="form1" runat="server">
        <asp:CheckBox ID="CheckBox1" runat="server" AutoPostBack="True" 
            oncheckedchanged="CheckBox1_CheckedChanged" Text="Box1" />
        <asp:CheckBox ID="CheckBox2" runat="server" Text="Box2" />
    </form>
    

    default.aspx.cs

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

    如果您选中复选框1,这将检查您的复选框2。将您的注意力吸引到AutoPostBack="True",如果您更改复选框1,它会导致您的页面回发到服务器。

    无论如何,您应该考虑这种解决方案。我不确切知道您想要实现什么,但它可能是通过 javaScript 在客户端上管理它的更好解决方案。

    【讨论】:

    • 是的,在我询问 autopostback 需要为 true 之后才知道
    【解决方案2】:

    您可以完全在 Javascript 上完成此操作

    <asp:CheckBox ID="CheckBox1" runat="server" onclick="changed(this);" />
    <asp:CheckBox ID="CheckBox2" runat="server" />
    

    如果选中Checkbox1,则JS函数将检查Checkbox2....

     function changed(element) {
            if (element.checked) {
                document.getElementById('<%=CheckBox2.ClientID%>').checked = element.checked;
            }
    
        }
    

    【讨论】:

      【解决方案3】:

      你犯了一个简单的错误。复选框的 Checked 属性未更改。

      if( checkbox1.Checked == true)
      {
         checkbox2.Checked == true;
      } 
      

      MSDN上阅读有关 CheckBox 属性的更多信息

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-04-16
        • 2019-03-26
        • 2019-11-28
        • 2014-05-30
        相关资源
        最近更新 更多