Getting a dropdownlist to check a checkbox in asp.

2019-07-27 05:36发布

问题:

<input runat ="server" type ="checkbox" id="helprequest" />     
<label for="helprequest">Help request</label>
<asp:DropDownList ID="options" runat="server" OnSelectedIndexChanged="checkHelpRequest">
    <asp:ListItem Text="Windows"></asp:ListItem>
    <asp:ListItem Text="Macintosh"></asp:ListItem>
    <asp:ListItem Text="Linux"></asp:ListItem>
    <asp:ListItem Text="Other"></asp:ListItem>
</asp:DropDownList>

In my codebehind, I have

protected void checkHelpRequest(object sender, EventArgs e)
{
    helprequest.Checked = true;
}

But when I select something on the dropdownlist, the checkbox, does not get marked as checked, how do I get the checkbox to appear as checked when I change the index on a dropdownlist?

回答1:

Your DropDownList does not have AutoPostBack='true' set. Without setting this, your dropdown will not post back when you change the selected index.

Just change it to:

<asp:DropDownList AutoPostBack="true" ID="options" 
      runat="server" OnSelectedIndexChanged="checkHelpRequest">

Without setting this, your checkHelpRequest method will still be called when your drop down changes index, but only after a postback is caused by some other control, like a button, or another DropDownList that does have AutoPostBack set.