2

How might a programmer work around scope limitations when writing event handling functions involving controls that are not declared via the GUI, but rather in the main source file?

Is it "acceptable" to declare such controls in global scope instead of Form1_Load() to solve this problem?

private void Form1_Load(object sender, EventArgs e)
{
    ComboBox t = new ComboBox();
    Button b = new Button();
    b.OnClick += b_OnClick;
}

private void b_OnClick(object sender, OnClickEventArgs e)
{
    s.Add("Hello s!"); // The object s is a ComboBox control generated in the Designer GUI
    t.Add("Hello t!");
}

// Line 10 is valid.
// Line 11 is invaid because t does not exist in the current scope.  How might one work around this issue?
user10478
  • 327
  • 1
  • 16
  • This is fine, because the references to your controls are added to `Controls` of your form, however to refer to one of your controls, you don't have any other way than looking it up in the `Controls` of your form. That's not very convenient. – King King Jun 22 '13 at 17:25

1 Answers1

3

I think that it is acceptable, if you look at the form.designer file you will notice that all the controls created using the designer are globals. So I think you could do the same in your own code.

However, I suppose that there are situations in which you don't need these controls otherwise the logic dictates that you build them directly with the designer and avoid that code.

Of course, your code above lacks of some absolutely necessary informations like the position, the size, a name and the most important of all. The Form.Controls.Add(control) statement, but I don't know if this is due to a simplification of your question.

Steve
  • 213,761
  • 22
  • 232
  • 286