jacob1123
jacob1123

Reputation: 361

Get Index of Control in an Control-Array

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)?

Upvotes: 2

Views: 2915

Answers (5)

Will Marcouiller
Will Marcouiller

Reputation: 24132

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.

Upvotes: 0

Yuriy Faktorovich
Yuriy Faktorovich

Reputation: 68667

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

Upvotes: 0

Neil N
Neil N

Reputation: 25258

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.

Upvotes: 1

Chris Taylor
Chris Taylor

Reputation: 53699

  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.

Upvotes: 1

Ian Jacobs
Ian Jacobs

Reputation: 5501

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.

Upvotes: 0

Related Questions