Adding "OnClick" event to code behind button - c#

So I've created a button, and I want to change its text by clicking on it.
This is my code behind (this is from the Page_Load code) :
Button InviteToGameBTN = new Button();
InviteToGameBTN.Click += new EventHandler(InviteToGameBTN_OnClick);
.
protected void InviteToGameBTN_OnClick(object sender,EventArgs e)
{
Button b1 = (Button)sender;
b1.Text = "Text changed";
}
What could be wrong ?
Thanks to all.

Not sure if this will 100% work but you may be able to use InviteToGameBTN.text to directly change it:
var button = FindViewById<Button>(Resource.Id.button1);
button.Click += delegate
{
button.Text = "changed text";
};
This was my little bit that I made in a new program, doesn't use an event handler but it uses the button.text to directly change its properties through the delegate { }

Related

Adding actions to programmatically added buttons

I am creating a program where it is required to have a list of buttons which relate to different things on the host computer.
I have achieved this as shown in the code below (example code):
Button btn = new Button();
btn.Name = "Button1";
btn.Text = "Item 1";
this.formLayoutProject.Controls.Add(btn);
This will eventually go into a for loop and more buttons will be on the flow layout, but i am starting small scale and working up so i don't get problems later.
This produces the button as expected (formatting will be done here too but haven't got that far).
What I am stuck on is how would I add a click event/right click event context menu onto the button?
I can put the click events in the code for buttons and items which will be fixed on the form and they work but I don't know how to do this dynamically as the buttons will be different on each target machine.
I have searched on Google but I haven't found what im looking for (probably due to the fact im not sure what the keywords are for the search).
How would I accomplish this?
You can add a button click event handler by using += operator on the event of your new btn object:
// Add 10 buttons dynamically.
// Bind to the same method.
for (var i = 1; i <= 10; i += 1)
{
Button btn = new Button();
btn.Name = "Button" + i;
btn.Text = "Item " + i;
this.formLayoutProject.Controls.Add(btn);
// Add handler.
btn.Click += btn_Click;
}
Now you just need to define the handler method:
private void btn_Click(object sender, EventArgs e)
{
// This is the button which was clicked.
var button = (Button)sender;
var buttonName = button.Name;
// Do some stuff.
// To detect certain mouse click events, cast e as a MouseClick.
MouseEventArgs mouseEvents = (MouseEventArgs)e;
// Now use the mouseEvents object to handle specific events based on the button clicked.
if (mouseEvents.Button == MouseButtons.Right)
{
// Right button clicked.
}
else if (mouseEvents.Button == MouseButtons.Left)
{
// Left button clicked.
}
}

Event handler for a dynamically added button

Code :
public partial class Form3 : Form
{
...
...
private void button1_Click(object sender, EventArgs e)
{
Panel p = new Panel();
TextBox diaryName = new TextBox();
Button b = new Button();
Label l = new Label();
diaryName.Font = new Font("Consolas", 12, FontStyle.Bold);
b.Font = buttonFont;
l.Font = buttonFont;
b.BackColor = Color.Wheat;
l.Text = "Diary Name : ";
b.Text = "Add Diary";
Point lbl = l.Location;
diaryName.Location = new Point(l.Location.X + l.Width + 5, lbl.Y);
Point txtbox = diaryName.Location;
b.Location = new Point(txtbox.X + diaryName.Width + 20, txtbox.Y);
p.Controls.Add(l);
p.Controls.Add(diaryName);
p.Controls.Add(b);
p.Location = new Point(12,272);
p.Size = new Size(20 + 20 + 20 + diaryName.Width + l.Width + b.Width, diaryName.Height);
// I need help here..
// b.Click += new EventHandler(); ???
this.Controls.Add(p);
this.Height += 50;
this.Width += 30;
this.FormBorderStyle = FormBorderStyle.Fixed3D;
}
...
}
The above code adds a panel that contains a label,a textBox and a button to the form , that's all working fine, my problem is that I want to handle click event of the dynamically added button (b) , In my event handling code I should be able to access the dynamically added TextBox (diaryName) for validation purposes, but I don't know how to do It. I tried adding another function within the same class Form3 , but since The textbox t is created within the button1_Click function, I am unable to access the textbox , so How can I get around this ?
I am new to c#, I have a Java background so is there any way in c# to declare event handlers like this
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
System.out.println("You clicked the button");
}
});
You can easy assign a handler to the button's event this way:
b.Click += new EventHandler(newButtonClick);
where
protected void newButtonClick(object sender, EventArgs e)
{
//Access your textbox like this
var myTextBox = this.Controls.OfType<TextBox>().FirstOrDefault(tb=>tb.Name == "diaryName");
if(myTextBox!=null)
{
//rest of your code here
}
}
However it's a poor practice. Your button will depend heavily on the objects created dynamically somewhere outside - that breaks encapsulation rule of OOP. Secondly - did you think what will happen if you'll click your original button (the one you showed your handler for) twice?
edit: When I've come to think about it, your method is not that dynamic really. It creates those controls on the fly, but they're not generic in any way - it's a static piece of code, that creates always the same result. So in this case I'd think about putting your new panel, textbox and button in the form as a public items and then initialize them inside your method.
It'd be even better to create them in the visual studio's designer already, hide them using Visible properties and then in button1_Click you could only change their sizes and show them up.
Ok, need to add event for button click,
1) So after you create new Button
Button b = new Button();
2) next add click event for that
b.Click += new EventHandler(b_Click);
3) and then write the actual function body for click event in your code
void b_Click(object sender, EventArgs e)
{
//Your code for click operation
}

Button not firing event on ASP.NET control Programmatically

I'm creating a Button on a ComboxChanged Event,
Button btn = new Button();
btn.ID = "btnNum1";
btn.Text = "Edit";
btn.Click += btnTest_Click;
pnl.Controls.Add(btn);
The event code is as followed
public void btnTest_Click(object sender, EventArgs e)
{
Button btn = (Button)sender;
Response.Write(btn.ID);
Response.Redirect("Page2.aspx");
}
I have tried, both Response.Write and Response.Redirect. None of them, works.
Same page gets refreshed. Does any one has any idea.
Button has to be created Dynamically, hence I can't try the Page_Init
I have also tried the CommandArgument event that also didn't work.
Any idea.
As Mt. Schneiders has mentioned in his comments under your question - if you dynamically add a control to a page, you must re-add it on the post-back. Just because you've added it as part of the event handler, does not mean that ASP.NET automatically creates the control on the post-back.
You need to store in the page the fact that the control was created - my personal preference would be to put the code in it's own function and set a ViewState value...
private void CreateButton()
{
Button btn = new Button();
btn.ID = "btnNum1";
btn.Text = "Edit";
btn.Click += btnTest_Click;
pnl.Controls.Add(btn);
ViewState["buttonAdded"] = true;
}
And call the function from your ComboxChanged event.
Then, on the Page_Load, you need to check to see if the button was added previously...
protected void Page_Load(object sender, EventArgs e)
{
if(Page.IsPostBack && ViewState["buttonAdded"] != null)
{
CreateButton()
}
}
(Note, I've stated Page_Load rather than Page_Init because the ViewState is not created at the Page_Init stage of the ASP.NET page life cycle)
when u added ur dynamic event handler it will store in particular control view state so when the page post back happened it will lose that event handler so u can implement load view state method which will come with page events code should be like
protected override void LoadViewState(object savedState)
{
base.LoadViewState(savedState);
}
Try this btn.Click += new EventHandler(btnTest_Click);.
Button btn = new Button();
btn.ID = "btnNum1";
btn.Text = "Edit";
btn.Click += new EventHandler(btnTest_Click);
pnl.Controls.Add(btn);
Assume this is the code that create the button :
If ddl.SelectedIndex > 0 Then
Dim b As New Button
b.ID = "mybutton"
b.Text = "i'm a button"
panel.Controls.Add(b)
AddHandler b.Click, AddressOf Button_Click
End If
Note the AddHandler ok it is exactly what you're looking for then
Private Sub Button_Click(ByVal sender As Object, ByVal e As EventArgs)
Dim b As Button = CType(sender, Button)
Dim l As Label = CType(Me.FindControl("testlabel"), Label)
l.Text = b.Text & " my id is " & b.ID.ToString
End Sub
that's all :)

Determining the source of the click event dynamically

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

Button Event Not Firing in WebControl

I'm attempting to create a "server control" that derives from WebControl. This needs to be done entirely in C# so that it can be compiled into a .dll. I am not interested in creating a user control with a .ascx file (I actually already have a "user control" but I want to add it to a library so I'm converting it).
My control is dead simple right now and I can't get a button event to fire:
public class ButtonWrapper : WebControl
{
protected Button button;
public event EventHandler<Events.GenericEventArgs<Tuple<int, string>>> ButtonClicked;
public void Button_Click(object o, EventArgs e)
{
ButtonClicked(this, new Tuple<int,string)(0, "abc"));
}
public void WHERE_DO_I_PUT_THIS_CODE()
{
button = new Button()
{
ID = "button",
Text = "Button"
};
button.Click += new EventHandler(Button_Click);
}
}
Where do I need to "create" the button? I currently have it in an overloaded CreateChildControls():
protected override void CreateChildControls()
{
this.Controls.Clear();
button = new Button()
{
ID = "button",
Text = "Button"
};
button.Click += new EventHandler(Button_Click);
this.Controls.Add(button);
this.ChildControlsCreated = true;
}
The control loads just fine, but when I click on the button, the page just refreshes and the event is never fired. I want to the button in ButtonWrapper to fire so that the parent page can listen. I think I'm close but I'm missing something simple.
Edit: I don't quite have the right event variables types for EventArgs passing and such when I was simplifying the problem for this question.
I created new solution and i tried it.
You can download from this link : http://dosya.co/download.php?id=51BACA121
I m at work and most of upload sites blocked. So i couldnt upload another site. If u cant download i can try find different upload site.

Categories