开发者

Get Index of Control in an Control-Array

开发者 https://www.devze.com 2023-01-01 10:39 出处:网络
I have a TextBox Array private 开发者_如何学JAVATextBox[,] Fields = new TextBox[9, 9]; and all the TextBoxes have got the same TextChanged-Event

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

精彩评论

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