开发者

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开发者_Go百科 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!


Try something like

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


Try

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


((Button)sender).Visible = false;


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;


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;


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


Try this:

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


Just use the sender.

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜