Reputation: 46710
I have a List
of labels which represent bars of a dynamically created mesh grid as part of a little game. The labels in question are the elements in red in the picture below.
I have two loops where each pass will create one of the labels. First loop creates the vertical labels where the other creates the horizontal.
// Build the next grid unit
lblGridUnit = new Label
{
Location = new Point(CurrentX, CurrentY),
BackColor = Color.Red,
AutoSize = false,
// The unit will be the size and width as defined by variables. Since this units are vertical the width and height are reversed.
Size = new Size { Width = gridUnitHeight, Height = gridUnitWidth },
Text = ""
};
lblGridUnit.Click += new EventHandler ( label_Click);
// Add the label the list and attach it to the form
gridUnits.Add(lblGridUnit);
ParentForm.Controls.Add(lblGridUnit);
I have a really basic event label_Click
that I am using for testing.
private void label_Click(object sender, EventArgs e)
{
Label clickedLabel = sender as Label;
if (clickedLabel != null)
{
clickedLabel.BackColor = Color.Aquamarine;
}
else
{
MessageBox.Show("Null");
}
}
I can interact with specific labels using the event and I can also find a specific label by using the list gridUnits
. Example being: GameBoard.GridUnits[5].BackColor = Color.Blue;
.
Issue is that I made the list so that I could use the index of a particular label to know where it is one the grid and determine neighboring grid units. How can I get the event to know its index in the List
?
I have not named any of my controls so I suppose I could name them with a numerical suffix but that seems like kludge so wondering if there is another option. Literally never coded c# until a couple of days ago.
Upvotes: 0
Views: 114
Reputation: 100547
Controls have Tag
property designed for this purpose - to store arbitrary piece of data that lets you map control to your model either directly or by some id/name.
Since you already creating all labels with code setting Tag
to grid index or some other more convenient value is trivial.
Note that since Tag
is of type object
you need to cast it to correct type of your data. If having very general click handler prefer target.Tag as MyType
to (MyType)target.Tag)
as you can check for null when using as
.
Upvotes: 2