简体   繁体   中英

C# how can I uncheck dynamically created radio buttons?

I'm dynamically creating some radio buttons in a form, and I would like users to have the ability to deselect them. Users' options should be select one, or select none(safer to use radio buttons than checkboxes). I tried using the EventHandler and creating an event, but I'm not having much luck getting it to work properly.

Here's what I've got making the buttons:

private void makeRadioButtons(string size, Panel pnl)
    {
        for (int i = 0; i < 2; i++)
        {
            RadioButton btn = new RadioButton();
            btn.AutoSize = true;
            btn.Name = i;
            btn.Text = i;
            btn.Location = new Point(100*i, 0);
            btn.Click += new EventHandler(radioHandler);
            pnl.Controls.Add(btn);
        }
}

And here is my event handler:

private void radioHandler(object sender, EventArgs e)
    {
        RadioButton rdo = sender as RadioButton;
        if(rdo.Checked)
        {
            rdo.Checked = false;
        }
        else
        {
            rdo.Checked = true;
        }
    }

When I compile I get the buttons, but can't select or deselect them. I feel like I'm close, but I just can't figure out what I'm doing wrong here.

RadioButtons are checked automatically by default. You can avoid that by setting their AutoCheck property to false when you create them.

Then you need to change your handler like this:

private void radioHandler(object sender, System.EventArgs e)
{
    RadioButton rbt = (RadioButton)sender;
    if (rbt.Checked)
    {
        rbt.Checked = false;
        return;
    }

    rbt.Checked = true;
    foreach (RadioButton r in pnl.Controls.OfType<RadioButton>())
        if (r != rbt) r.Checked = false;
}

So if the clicked button was checked, it is unchecked. If it was not checked, we check it and uncheck all the others (this is necessary since we set AutoCheck to false ).

It s your event handler code that makes the mess.

Radiobuttons are automatically checked/unchecked when user clicks.

Your code makes the opposite !

Edit

Just removing of the handler is needed.

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