1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

Accessing controls at runtime

Discussion in 'C#' started by imported_hi5.ankit, Oct 5, 2010.

  1. imported_hi5.ankit

    imported_hi5.ankit New Member

    Joined:
    Oct 5, 2010
    Messages:
    1
    Likes Received:
    0
    Trophy Points:
    0
    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??
     
  2. Love.NET

    Love.NET New Member

    Joined:
    Nov 20, 2010
    Messages:
    14
    Likes Received:
    0
    Trophy Points:
    0
    Home Page:
    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 !
     
  3. servalsoft

    servalsoft New Member

    Joined:
    Apr 17, 2010
    Messages:
    10
    Likes Received:
    0
    Trophy Points:
    0
    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 :)))
     

Share This Page