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 ...
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With