Search code examples
c#typesvoidsender

Get sender's element type (Button, PictureBox etc..)


I am using a void for multiple elements. Such as buttons, labels, pictureboxes....

But i need to modify some of the sender's variables. Such as name, top, left etc... This is my code:

private void FareSurukle(object sender, MouseEventArgs e)
{
   MessageBox.Show(((TYPE_COMES_HERE)sender).Name);      
}

If i edit "TYPE_COMES_HERE" to PictureBox, it works on PictureBox. But it gives error on other elements. Like buttons.

Is it possible to get and modify sender's variables without declaring it's type? Or can i make a type check of sender with if's?


Solution

  • I need to modify some of the sender's properties, such as name, top, left

    You don't have to inspect the exact type for that. The controls you mention all inherit from a base class that contains all these properties, aptly named Control:

    MessageBox.Show(((Control)sender).Name);