(resolved) getting control name on click event
First of all.....sorry for the super long post. I don't like them either. Just trying to include information.
I have added several text boxes dynamically. They are a 2d array, btn[x,y].
I gave them all the same click event. The problem is that when one of them is clicked I need to know which one was clicked. I don't know how to extract the control name out of the arguments (Object sender, System.EventArgs e). I know that you can use:
Code:
if(sender.Equals((object)controlName))
//do something
but there is no way I want to sit in a double nested loop to find which button was clicked.
To help, I've included some code snippets from my project:
Here is the routine that creates the buttons:
Code:
private void createSockets(int iX, int iY)
{
int x=0,y=0;
p_socks=new Button[iX,iY];
try
{
for(x=0;x<iX;x++)
{
for(y=0;y<iY;y++)
{
//no need to create sockets again
if(socketsCreated)
return;
//generate socket name
string butName=x.ToString()+(char)(y+'A');
//add new buttons
p_socks[x,y]=new Button();
this.Controls.Add(p_socks[x,y]);
p_socks[x,y].Location = new System.Drawing.Point(10, 10);
p_socks[x,y].Name = "socks"+x+y;
p_socks[x,y].Size = new System.Drawing.Size(20, 20);
p_socks[x,y].TabIndex = 20;
p_socks[x,y].Text = ""; //"socks"+x+y;
p_socks[x,y].BackColor=p_backColor;
p_socks[x,y].Visible=true;
p_socks[x,y].Click+=new System.EventHandler(sockClickHand);
}
}
this.Refresh();
}
catch(Exception err)
{
errhand(err);
}
}
And here is the click event:
Code:
private void sockClickHand(Object sender, System.EventArgs e)
{
//this only displays the type of controls, not the name
System.Windows.Forms.MessageBox.Show("You have clicked button " + Tag.ToString());
}
Re: getting control name on click event
I got mightily confused reading this until I realised it was a question and not a real code bank post.
casting the object sender to a button will give you the button that raised the click event.
Code:
private void sockClickHand(Object sender, System.EventArgs e)
{
Button btn = (Button)sender;
//now do whatever you want with the button.
}
Re: getting control name on click event
Re: getting control name on click event
Code:
private void sockClickHand(Object sender, System.EventArgs e)
{
Button btn = sender as Button;
if(null != btn)
{
//now do whatever you want with the button.
}
}
I prefer this because 'as' returns null if you try an invalid cast, whereas (Button)sender will throw an error on an invalid cast.
Re: getting control name on click event
Thx. Worked great!
Sorry about posting in the wrong section. My mistake.