如何确定事件内的标签索引。

时间:2016-02-17 03:20:52

标签: c# controls

我有List个标签,代表动态创建的网格网格的条形图,作为小游戏的一部分。有问题的标签是下图中红色的元素。

enter image description here

我有两个循环,每个传递将创建一个标签。第一个循环创建垂直标签,另一个创建水平。

// 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);

我有一个真正的基本事件label_Click,我正在使用它进行测试。

private void label_Click(object sender, EventArgs e)
{
    Label clickedLabel = sender as Label;

    if (clickedLabel != null)
    {
        clickedLabel.BackColor = Color.Aquamarine;
    }
    else
    {
        MessageBox.Show("Null");
    }
}

我可以使用该事件与特定标签进行交互,我也可以使用列表gridUnits找到特定标签。例如:GameBoard.GridUnits[5].BackColor = Color.Blue;

问题是我制作了列表,以便我可以使用特定标签的索引来知道它在哪个网格中并确定相邻的网格单元。如何让事件在List

中了解其索引

我没有命名任何控件,所以我想我可以用数字后缀命名它们,但这看起来像kludge所以想知道是否还有其他选项。从字面上看,直到几天前才编码c#。

1 个答案:

答案 0 :(得分:2)

控件具有为此目的设计的Tag属性 - 用于存储任意数据,使您可以直接或通过某个ID /名称将控件映射到模型。

由于您已经创建了代码设置为Tag的所有标签到网格索引,或者其他一些更方便的值是微不足道的。

请注意,由于Tag的类型为object,因此您需要将其强制转换为正确的数据类型。如果使用非常一般的点击处理程序,请将target.Tag as MyType更改为(MyType)target.Tag),因为在使用as时可以检查为空。

相关问题