简体   繁体   中英

C# RadioButton Checked anomalous

I have an aspx page containing this code.

<asp:RadioButton id="rb_Vero" ClientIDMode="Static" GroupName="RegularMenu" Text="" runat="server" Checked="true"/>        
<asp:RadioButton id="rb_Falso" ClientIDMode="Static" GroupName="RegularMenu" Text="" runat="server"/> 

On the cs page, this is behind.

if (verificata == true) 
   rb_Vero.Checked = true;
else 
    rb_Falso.Checked = true;

When the "verificata" variable changes (true/false), the radio button does not always change.

firstly, if you are hoping for the checkboxes to initiate an event on the server you need the attribute AutoPostback = "true" .

now depending on how verificata gets set, don't you need to uncheck the other checkbox:

// you need to choose an appropriate event for the block below
if (verificata) 
{
   rb_Vero.Checked = true;
   // add this
   rb_Falso.Checked = false;
}
else 
{
   rb_Falso.Checked = true;
   // add this    
   rb_Vero.Checked = false;
}

First off, I presume you hard-coded rb_Vero to true for testing purposes in the ASPX? Remove that attribute. You will perform the logic on your Page_Load.

Secondly, as @Ted said, make sure AutoPostback is set to true for both controls.

protected void Page_Load(object sender, EventArgs e)
{
    // Sample only - update to load from ViewState on Postbacks
    if (verificata == "true") 
    {
        rb_Vero.Checked = true;
        rb_Falso.Checked = false;
    }
    else 
    {
        rb_Vero.Checked = false; 
        rb_Falso.Checked = true;
    }
}

Finally, there is a known issue with list controls. Unless you override the SaveViewState and LoadViewState methods to store and retrieve these values, it won't work.

protected override void LoadViewState(object savedState)
{
    base.LoadViewState(savedState);

    // Sample snippet - update for your controls
    if (ViewState["Checked"] != null)
        checked = (bool)ViewState["Checked"];
}

protected override object SaveViewState()
{
    // Sample snippet - update for your controls
    ViewState["Checked"] = checked;

    return base.SaveViewState();
}

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