Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# - Name a radio button with a string and access its properties

I have a lot of repeating code that I am trying to get rid of but I have some issues.

Here is the main one:

I got several timers, all identifed with numbers, all have a button to trigger them but it makes the same code repeat over and over for no reason, example:

private void buttonTimer1_Start_Click(object sender, EventArgs e)
    {
        if (radioButtonTimer1_CountDown.Checked)
        {

And so on...

I was already able to create one event for the buttons and to get the number of the button with:

Button button = sender as Button;
var buttonName = button.Name;
var resultString = Regex.Match(buttonName, @"\d+").Value;
var buttonID = Int32.Parse(resultString);

So what I would like to do, if at all possible, would be to use something like:

if ("radioButtonTimer"+buttonID+"_CountDown".Checked)

But it's not possible to access the property ".Checked" from a string.

What would be the best way to handle that issue? I have a lot of text fields, radio buttons and what not I need to make "dynamic" that way.

Thanks a lot for your time and help.

like image 636
Dyr Fenrir Avatar asked Oct 19 '25 15:10

Dyr Fenrir


2 Answers

Use the Controls.Find()-Method.

http://msdn.microsoft.com/en-us/library/system.windows.forms.control.controlcollection.find%28VS.80%29.aspx

This could look like this:

Control[] ArrControls = this.Controls.Find("radioButtonTimer"+buttonID+"_CountDown");
if(ArrControls.Where(c => (c as RadioButton).Checked).ToList().Count > 0)
{
  // Checked Radio Buttons
}
else
{

}
like image 71
kassi Avatar answered Oct 21 '25 04:10

kassi


Assuming WinForms:

        Button button = sender as Button;
        var resultString = Regex.Match(button.Name, @"\d+").Value;
        Control[] matches = this.Controls.Find("radioButtonTimer"+resultString+"_CountDown", true);
        if (matches.Length > 0 && matches[0] is RadioButton)
        {
            RadioButton rb = matches[0] as RadioButton;
            if (rb.Checked)
            {
                // ... do something in here ...
            }
        }
like image 34
Idle_Mind Avatar answered Oct 21 '25 03:10

Idle_Mind