views:

112

answers:

5

I have a TextBox Array

private TextBox[,] 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)?

A: 

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.

Ian Jacobs
+1  A: 
  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.

Chris Taylor
+1  A: 

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.

Neil N
A: 

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);
    }
}
Yuriy Faktorovich
A: 

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.

Will Marcouiller
Works only with one-dimensional Arrays as far as I can see.
Cocaine112358