I am new to C# and I am making a small tic-tac-toe game using WPF. However, I would like to make my code compact and would like to create a method which will take button click event as argument and modify the button. For the time being, this is what I am trying to do:
Button.IsEnabled = false;
Button.Content = "X";
I want to make a event which will do this job when called inside a button click event and hence I will not need to copy this code for every button.
IN the xaml, add the event handler to the button:
<Button Click="Button_Click" />
(add the same handler to all buttons)
in the code behind, cast the sender to a button:
private void Button_Click(object sender, RoutedEventArgs e)
{
var button = sender as Button;
if (button != null)
{
button.IsEnabled = false;
button.Content = "X";
}
}
Attach the event handler and use the sender:
Button.Click += this.Button_Click;
private void Button_Click(object sender, RoutedEventArgs e)
{
Button button = sender as Button;
if (button != null)
{
button.IsEnabled = false;
button.Content = X;
}
}
Related
I'm using a Button in a class. When the button is pressed, it should call a routine with the button's corresponding text. How do I convert the sender into a String_Entry? Also, I'm quite a newbie regarding object oriented/class programming, so comments are welcome.
public class String_Entry
{
public TextBox textbox;
public Button send;
// other stuff
public String_Entry()
{
textbox = new TextBox();
send = new Button();
send.Click += new System.EventHandler(this.bSend_Click);
// put in GUI, set parameters and other stuff
}
// other stuff
private void bSend_Click(object sender, EventArgs e)
{
// Trying to get the corresponding String_Entry from the Button click event
Button cntrl = (Button)sender;
String_Entry entry = (String_Entry)(cntrl.Parent);
parse.ProcessHexLine(entry);
}
}
Your solution of encapsulating a button with a textbox and the event handler is sound. It just goes wrong in the event handler:
private void bSend_Click(object sender, EventArgs e)
{
Button cntrl = (Button)sender;
String_Entry entry = (String_Entry)(cntrl.Parent);
parse.ProcessHexLine(entry);
}
Firstly, there is no point to doing anything with sender as it'll be the same as the field send. Next cntrl.Parent will give you a reference to the Form, or other container object, that contains the button, not this instance of String_Entry. To access that, use this. So you can change the event handler to:
private void bSend_Click(object sender, EventArgs e)
{
parse.ProcessHexLine(this);
}
I have a set of buttons that are added dynamically. As the user keeps clicking the buttons, new buttons are added to the window. I am using a winforms. I am binding the onclick event of all these buttons to the same function. I am using the following code.
System.EventHandler myEventHandle= new System.EventHandler(this.Button_Clicked);
Once a new dynamic button is created I add the event handler with the following code:
b1.Click += myEventHandle;
Now in the function Button_Clicked() I want to get the Button which invoked this event. I want to disable this Button so that it cannot be clicked again and I want the name of the Button that was clicked as I want to do various actions depending on button name. I am newbie in C#.
This is what I have tried so far, but doesn't seem to work:
Button b = sender as System.Windows.Forms.Button;
b.Font = new Font(b.Font, FontStyle.Bold);
Console.WriteLine(""+b.Name);
b.Enabled = false;
Use the sender of the event
if(sender is Button)
{
Button b = sender as Button;
b.Enabled = false;
///something = b.Name;
}
Well, your Button_Clicked method must look like
void Button_Clicked(object sender, EventArgs e) {
Button clickedButton = (Button)sender;//if sender is always a Button
clickedButton.Enabled = false;
}
I want to create a method in code behind that creates a button and places it in a PlaceHolder. I want this button to have a Click event.
After calling the "test" method button is placed correctly but the click event is not called.
private void test()
{
Button linkBtn1 = new Button();
linkBtn1.Text = "linkBtn1";
linkBtn1.OnClientClick = "return false;";
linkBtn1.Click += new EventHandler(linkBtn1_Click);
PagesPlaceHolder.Controls.Add(linkBtn1);
}
void linkBtn1_Click(object sender, EventArgs e)
{
throw new NotImplementedException();
}
Removing the OnClientClick = "return false;" is necessary but not sufficient to get this to work. If you want the event handler on the dynamically added button to be triggered, you'll need to add this button every time the page loads.
One simple way would be to save the fact that the button has been added in ViewState, and then check that on PageLoad, and re-add the button if needed.
Here's a sample that works for me (and throws the exception when clicked)
protected void Page_Load(object sender, EventArgs e)
{
//if the button was added previously, add it again
if (ViewState["Added"] != null && (bool)ViewState["Added"])
addButton();
}
//this is the method that adds the button
protected void add_Click(object sender, EventArgs e) {
ViewState["Added"] = true;
addButton();
}
private void addButton() {
Button linkBtn1 = new Button();
linkBtn1.Text = "linkBtn1";
linkBtn1.Click += new EventHandler(linkBtn1_Click);
placeholder1.Controls.Add(linkBtn1);
}
void linkBtn1_Click(object sender, EventArgs e) {
throw new Exception("Button Click Event Triggered. Hello yellow screen!!!");
}
As #oleksii points out, have the clientside code is returning false so the form never gets submitted. You need to comment this out, then your event handler should fire.
I have A|B|C|D.....|Z link buttons on web forms . Now i have to add single event in code behind to handles all link buttons. How to do with C# asp.net
If you didn't mean on dynamicaly setting events, you just set the same ethod in OnClick event for all buttons:
<asp:LinkButton id="btnA" Text="A" runat="server" OnClick="myMethod" />
<asp:LinkButton id="btnB" Text="B" runat="server" OnClick="myMethod" />
in code behind:
potected void myMethod(object sender, EventArgs e)
{
....
}
This should work...
Also, instead of OnClick, you could set CommandName and additionaly set CommandArgument for each LinkButton, to pass different parameters. Then, in code behind method signature, you should set CommandEventArgs instead of EventArgs.
Associate the eventhandler of these Buttons or LinkButtons at Page_Init and check the sender control that made the request.
protected void Page_Init()
{
LinkButton1.Click += Link_Click;
LinkButton2.Click += Link_Click;
LinkButton3.Click += Link_Click;
LinkButton4.Click += Link_Click;
}
cast the control according to your postback enabled controls either it is button or linkbutton and check for some control perperty of that control to identify that control.
private void Link_Click(object sender, EventArgs e)
{
LinkButton button = sender as LinkButton;
if (button.Text == "LinkButton1")
{
Response.Write("<script>alert('link1');</script>");
}
else if (button.Text == "LinkButton2")
{
Response.Write("<script>alert('link2');</script>");
}
}
you can check for the control as:
Button button = (Button)sender;
if(button is Button1)
{
..
}
Use like :
button1.Click += new EventHandler(Button_Click);
button2.Click += new EventHandler(Button_Click);
button3.Click += new EventHandler(Button_Click);
......
That would subscribe all the events to the single event handler.
You can get which button has been clicked on event handler :-
private void Button_Click(object sender, System.EventArgs e)
{
Button b = (Button) sender;
Label1.Text = b.ID;
}
I am using the following code to add buttons to a list:
for (int i=0; i < mov.Theat.Count(); i++)
{
StackPanel st=new StackPanel();
st.Orientation=System.Windows.Controls.Orientation.Horizontal;
st.HorizontalAlignment = HorizontalAlignment.Center;
TextBlock tx = new TextBlock();
tx.Text=mov.Theat[i];
st.Children.Add(tx);
TextBlock tx2=new TextBlock();
tx2.Text=mov.Time[i];
st.Children.Add(tx2);
Button test = new Button();
test.Width=450;
test.Content = st;
test.Click += new RoutedEventHandler(Button_Click);
theatlist.Items.Add(test);
}
As for the event handler, it is shown below:
void Button_Click(object sender, RoutedEventArgs e)
{
Theat_Data TD=(App.Current as App).Theat.First(theat => theat.Name=="");
PhoneApplicationService.Current.State["Theat"] = TD;
this.GoToPage(ApplicationPages.Theat);
}
I want to pass some variable about the selected button in the even handler so how can this be done? And if this is not possible, then what options do I have to identify the button and pass some data about it to the event handler?
I assume your business object is called Thead_Data and you would like to have access to this object from within your Click-method:
During creation, attach your data object to the DataContext or the Tag property:
Button test = new Button(){DataContext=Theat[i]};
Within your event handler, cast the DataContext or the Tag-property to your business-object:
void Button_Click(object sender, RoutedEventArgs e){
Button btn=(Button)sender;
Theat_Data td=(Theat_Data)button.DataContext;
...
}
You can access the sender like this:
void Button_Click(object sender, RoutedEventArgs e)
{
var clickedButton = sender as Button;
}
I'm not sure I completely understand what you are asking, but the "sender" param of the event handler is the button. You should just be able to cast it:
Button b = (Button)sender;
You could write your own event handler and add your custom data in the event args.