简体   繁体   中英

Why does this event fire asynchronously?

I've got this code to prevent two opposite radio buttoms from both being checked:

RadioButton rbUSCitizenOrPermResY = null;
RadioButton rbUSCitizenOrPermResN = null;

. . .

rbUSCitizenOrPermResY = new RadioButton
{
    CssClass = "finaff-webform-field-input"
}; // doesn't allow assignment to CheckedChanged above
rbUSCitizenOrPermResY.CheckedChanged += new EventHandler(rbUSCitizenOrPermResY_Changed);

. . .

private void rbUSCitizenOrPermResY_Changed(object sender, EventArgs e)
{ 
    if (rbUSCitizenOrPermResN.Checked)
    {
        rbUSCitizenOrPermResN.Checked = false;
    }
}

So, if the "Yes" radio button is checked, it unchecks the "No" radio button if the "No" radio button is checked.

Supposedly.

In actuality, this event handler is entered, but not when the radio button is clicked. Rather, it fires later, after I click the "Save" button. Is this an asynchronous event handler, that just wakes up whenever it feels like it? If so, how can I get it to "straighten up and fly right"/"shape up or ship out"?

It's taken me a while to figure out what you are describing, because I'm used to thinking about this stuff client side, not server side. But since you are doing server side, I think you need to introduce some kind of grouping construct for your radio buttons. I just tried an example app where I used a RadioButtonList containing ListItems (rather unintuitively, they are not called Radiobuttons). But using the RadioButtonList to group them, they behave correctly on the client side, ie they are exclusive. Clicking on one unselects the other. Here is the markup I used (does this fit your scenario?):

<asp:RadioButtonList ID="RadioButtonList1" runat="server">
    <asp:listItem ID="rad1" runat="server"></asp:listItem>
    <asp:listItem ID="rad2" runat="server"></asp:listItem>
</asp:RadioButtonList>

The listitem control got translated in the designer file as a System.Web.UI.WebControls.ListItem

Incidentally, I mocked this up as a Web Form application in Visual Studio. I don't have any Sharepoint stuff installed, but I think the principle is the same (I hope).

The generated HTML ended up looking like this:

<table id="MainContent_RadioButtonList1">
    <tr>
        <td><span ID="rad1"><input id="MainContent_RadioButtonList1_0" type="radio" name="ctl00$MainContent$RadioButtonList1" value="" /></span></td>
    </tr>
    <tr>
         <td><span ID="rad2"><input id="MainContent_RadioButtonList1_1" type="radio" name="ctl00$MainContent$RadioButtonList1" value="" /></span></td>
    </tr>
</table>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM