Change dropdownlist value if checkbox is checked on autopostback ASP.NET

2k views Asked by At

I want to change the DropDownList1 value if Checkbox1 is checked in my Web Application.

The Default Value on the DropDownList1 when the page loads should be "0" When the Checkbox1 is clicked, the DropDownList1 value should be "1"

The following code which I have done throws a runtime error.

My aspx snippet:

<asp:CheckBox ID="Checkbox1" runat="server" 
                                         class="itemCheck" AutoPostBack="True" CausesValidation="True" />
                                </td>
                                <td >
                                    &nbsp;<asp:DropDownList ID="DropDownList1" runat="server" Height="16px" 
                                        Width="138px">
                                        <asp:ListItem Selected="True">0</asp:ListItem>
                                        <asp:ListItem>1</asp:ListItem>
                                        <asp:ListItem>2</asp:ListItem>
                                        <asp:ListItem>3</asp:ListItem>
                                    </asp:DropDownList>

My code behind file:

protected void Page_Load(object sender, EventArgs e)
{
        string val = "1";
        ListItem checkItem = DropDownList1.Items.FindByValue(val);
        if (checkItem != null)
        {
            DropDownList1.ClearSelection();
            checkItem.Selected = true;
        }
}
2

There are 2 answers

1
Paul On

Your listitems are missing a value attribute.

<asp:ListItem Value="1">1</asp:ListItem>
1
Imad On

Remove your Page_Load code and replace checkbox markup with below mark up

  <asp:CheckBox ID="Checkbox1" runat="server" class="itemCheck" AutoPostBack="True" CausesValidation="True" OnCheckedChanged="Checkbox1_CheckedChanged"/>

and write your logic in this event

protected void Checkbox1_CheckedChanged(object sender, EventArgs e)
{
     If (Checkbox1.Checked) DropDownList1.SelectedValue = "1";
     else DropDownList1.SelectedValue = "0";
}