laz
laz

Reputation: 67

c# replacing integer

I have 50 buttons in my project as all are linked, when pressed, to a method. And now, when a button has been pressed I want it to go invisible. Since I don't want my code to contain 50 IF statements to check which button that has been pressed:

If(sender == Button1)
{     
    Button1.visible = false;
} 

This code gets very long if I ill have almost the same block of code when only the button name changes 50 times. Is there anyway to this in another way to get a shorter code?

Maybe: If a String variable contains the name of the button?

string buttoncheck = Button1;

And then in the upper code insert buttoncheck instead of Button1 since buttoncheck contains the value/name of Button1?

Thanks!

Upvotes: 2

Views: 841

Answers (8)

Dan J
Dan J

Reputation: 16708

By casting it to a Button, you can just use the reference provided by sender to set the visibility of the button that fired the event.

if(sender is Button)
{
  ((Button)sender).Visible = false;
}

Upvotes: 2

Denis Biondic
Denis Biondic

Reputation: 8201

If 50 buttons share same functionality, subscribe their Click event to the same event handler, and do this:

Button button = sender as Button;    
if (button != null)
   button.Visible = false;

Upvotes: 2

Dave Ferguson
Dave Ferguson

Reputation: 1456

Just use the sender.

var button = (Button) sender;
button.Visible = false;

Upvotes: 0

Jean-Philippe Leclerc
Jean-Philippe Leclerc

Reputation: 6805

In your event, you have a sender.

You can cast your sender to you Button object type.

var button = sender as Button;

if(button != null)
    button.Visible = false;

Upvotes: 2

carlbenson
carlbenson

Reputation: 3207

Try this:

Button button = sender as Button;
button.Visible = false;

Upvotes: 1

YetAnotherUser
YetAnotherUser

Reputation: 9356

Try something like

var x = sender as Button;
if(x != null){
    x.Visible = false;
}

Upvotes: 7

user703016
user703016

Reputation: 37955

((Button)sender).Visible = false;

Upvotes: 2

Bala R
Bala R

Reputation: 108957

Try

Button button = (Button) sender;
button.Visible = false;

Upvotes: 3

Related Questions