I've come across a problem, that is probably seen pretty often, but has never really been discussed here.
In my Gui, I'm adding Controls in a for loop to a Flowpanellayout. The point is to display "reports" from a database. It has to be dynamic, because the number of reports can be different from day to day.
Pseudocode Adding Gui Elements:
for(int i = 0; i < reports.Count; i++)
{
TextBox textboxPerson = new TextBox();
textboxPerson.Name = "TextboxName" + i;
textboxPerson.Text = reports[i].Name;
textboxPerson.TextChanged += new EventHandler(this.textboxPerson_TxtChanged);
Label labelToChange = new Label();
labelToChange.Name = "label"+i;
labelToChange.Text = "";
flowlayoutPanel.Controls.Add(textboxPerson);
flowlayoutPanel.Controls.Add(labelToChange);
}
Event Handler:
private void textboxPerson_TextChanged(object sender, EventArgs e)
{
//So far, I'm only getting the number of the Textbox that changed.
}
Here is, where I need your advise. The Textboxs and Labels are matching (iE, Texbox1 is as you can see connected to Label1). But how do I address one Control in particular?
You can use the Tag
property of the controls, for instance. In your loop, you can assign the Label
to the Tag
property of the TextBox
like this:
TextBox textboxPerson = new TextBox();
// do the stuff with the text box
Label labelToChange = new Label();
// do the stuff with the label
textboxPerson.Tag = labelToChange
Then you can get to the Label
in the TextChanged
event of the TextBox
:
private void textboxPerson_TextChanged(object sender, EventArgs e)
{
//So far, I'm only getting the number of the Textbox that changed.
Label theLabel = (sender as TextBox).Tag;
theLabel.Text = "whatever should go here";
}