I create an array of 16 text boxes, etc in code. I need to detect which one is clicked. I have created an event handler for each that points to the same handler routine for all 16

for(int box = 0; box < 16; box ++)
{
    txtArray[box].Click += new System.EventHandler(txtArray_n_Click);
}

There I get stuck trying to identify which one called the handler. Been reading up on Delegates, but I'm not sure which direction to travel from here. I could spend a lot of time on that path to no profit other than my own education!

Any pointers?

Hi, When create the textbox give unique name. And in Click event you receive the sender object, Typecast it to textbox and check the name you want.

Ex

TextBox[] textArray;
    public Form1()
    {
        InitializeComponent();
        textArray = new TextBox[10];
        for (int i = 0; i < 10; i++)
        {
            TextBox textBox = new TextBox();
            
            textBox.Name = "Name" + i ;
            textBox.Location = new Point(0, (i + 1) * textBox.Height);
            textArray[i] = textBox;
            textArray[i].Click += new EventHandler(ArrayOnClick);
            this.Controls.Add(textBox); 
        }
    }
private void ArrayOnClick(object sender, EventArgs e)
    {
        TextBox textBox =(TextBox) sender;
        MessageBox.Show(textBox.Name ); 
        switch ( textBox.Name ){
            case "Name0":
                //Code for Name0 TextBox
                
                break;
            case "Name1":
                //Code for Name1 TextBox
                break;

        }
    }

Yes. That will do nicely.

Your
textBox.Name = "Name" + i ;

becomes, for me
txtArray.Name = i.ToString();

[Shame on me. Why did I not think of giving them a name!]

Then I pick up your line in the handler

TextBox textBox =(TextBox) sender;

And I’m away, with a reference to which one is knocking at the door.

I was frustrated that the event handler did not pass me enough info in the Sender object or EventArgs to determine which control I was dealing with. I could determine the text in the box but not the name. IT HAD NO NAME.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.