当前位置: 动力学知识库 > 问答 > 编程问答 >

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.

网友答案:

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
{

}
网友答案:

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 ...
            }
        }
分享给朋友:
您可能感兴趣的文章:
随机阅读: