开发者

Get Index of Control in an Control-Array

I have a TextBox Array

private 开发者_如何学JAVATextBox[,] Fields = new TextBox[9, 9];

and all the TextBoxes have got the same TextChanged-Event

void Field_Changed( object sender, EventArgs e )

Is there a way to get the Index of the sender in the Array (without giving each TextBox it's own EventHandler)?


  1. Do you really need the index, the sender is a reference to the instance that send the request.

  2. If the answer to 1 is yes, you can put the index in the 'Tag' property of the textbox and then query that.

  3. Alternatively you can search the array for the instance that matches the sender argument of the event.


You'll pretty much have to loop through your array and do a reference equality check on each text box.

Either that or assign the index to the tag when you insert the controls to the array. But this is a micro optimization not really worth it.


Try giving each textbox it's own Tag or Name on initialization, Then you can cast sender to a TextBox and look at either of those properties.


You can iterate through the objects and find the one whose reference equals the sender:

for (int i = 0; i < 9; i++)
{
    for (int j = 0; j < 9; j++)
    {
        if (Object.ReferenceEquals(sender, Fields[i, j])) 
            Console.WriteLine(i + " " + j);
    }
}


Taking an eye out the Array Members might help.

The ones you're particularly looking for are the IndexOf() methods. There are multiple overloads. Choose the one that best suits your needs.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜