I have 10 buttons and a textbox on my widow form. 11th button to fire the operation. Task is that i need to input a no. in the textbox ranging from 1-10, and press the fire button. This should change the forecolor of the respective button in the form. Suppose i enter 5 and press fire. This should change the forecolor of the button5. i.e button5.forecolor=.... I am already addressing the issue by using if statements like. if textbox1.text == 1 button1.forecolor = red; if textbox2.text == 2 button2.forecolor = red; But this is hectic incase i have around 20 buttons. So how to access the control button and its properties by specifying its id at the runtime??
I think you can put all your buttons in an array or a collection of button. Your problem will be more complex if suppose that when "1" input in the textBox, the button5 not button1 is colored..ect. Or each button in your form will be colored with various colors. So sometimes I think we have to handle every if statement for every button even when there are more than 20 buttons. You can use "switch ...case" statement instead. Thanks !
Here is how I would handle that: everything on your form is a control, and I believe they are indexed in the order you add them to your Form. Since your form already has a collection of all the controls it contains you can simply do the following: Code: int controlNumber = (int)(txtInputNumber.Text); int count = 0; foreach (control c in myForm.Controls) { if (count == controlNumber) { ///do something i.e c.forecolor = ...... break; // <--- Exit the loop since done } else ++count; //increase the counter if we are not at the required control } I wrote the above on the fly so you'll probably need to modify a little bit to use it in your program. I hope it helps ))