1

I'm trying to create a webform in asp.net/c# that uses checkboxes. What I would like to do is automatically check one box if another is checked

for example if button2 is checked, automatically check button1, but don't automatically check if button1 is checked

tried doing an if statement that handles this like:

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

but this didnt work. anyone point me in right direction of where to look on how to do this.

4

3 回答 3

2

You mean something like this?

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;
}

This will check your checkbox2 if you check checkbox1. Draw your attention on AutoPostBack="True" which causes your page to postBack to the server if you change checkbox1.

Anyway you should think over this kind of solution. I don't know exactly what you want to achieve, but it may be a better solution to manage this on client via javaScript.

于 2012-08-29T19:13:43.640 回答
1

You can do this entirely on Javascript

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

And then the JS function that will check Checkbox2 if Checkbox1 is checked....

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

    }
于 2012-08-29T19:11:16.770 回答
1

you are doing a simple mistake. Checkboxes have a Checked property not changed.

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

Read more about CheckBox properties on MSDN

于 2012-08-29T19:12:27.957 回答