Button Event Not Firing in WebControl - c#

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.

Related

User Control Form Click event not clicking on label C#

I have a problem with User form Click that I am trying to make in C# using a usercontrol.
It consists of a picturebox and a label. I want to call the click event but the picturebox and the label don't do anything when I click them. Only the background area of the usercontrol does what I want it to do. Any ideas?
here's my code
for (int i = 0; i < listitems2.Length; i++)
{
listitems2[i] = new declined();
//adding sample data to each dynamic user
listitems2[i].dicon = dicon[i];
listitems2[i].did = did[i];
listitems2[i].dname = dname[i];
//adding data to flow layout panel
flowLayoutPanel2.Controls.Add(listitems2[i]);
// below line will assing this (usercontrolclick) event to every user control created dynamically
listitems2[i].Click += new System.EventHandler(this.UserControl_Click);
}
for click function
void UserControl_Click(object sender, EventArgs e)
{
string ctrlName = ((UserControl)sender).Name;
applicable obj = (applicable)sender;
studid.Text = obj.id;
studname.Text = obj.name;
pictureBox1.Image = obj.icon;
}
You added OnClick handler to your UserControl, so only clicks made on UserControl will be registered. To enable Click event for all the controls on your form, you need to add your click handler to all other controls.
But, according to your code, you're adding click handling on form where your control is located. In this case, you cannot register clicks on control from "outside" (you can by making Label and PictureBox controls public and adding handlers for their OnClick events but that is wrong way to do it)
My suggestion is to make custom event on your form and raise it on Form, Label and PictureBox click, and then make handler for that event on form which holds your UserControl.
Something like this:
//make custom eventHandler on your UserControl
[Browsable(true)]
public event EventHandler UserControlClicked;
//constructor
public UserControl1()
{
InitializeComponent();
//after intialize compoment add same handler for all three controls
this.Click += ControlClicked;
this.pictureBox1.Click += ControlClicked;
this.label1.Click += ControlClicked;
}
//this method will "catch" all clicks
private void ControlClicked(object sender, EventArgs e)
{
//raise event
UserControlClicked?.Invoke(this, e);
}
and on form where your custom control is, add handler for UserControlClicked (maybe with cast, I don't know what listItems2[i] contains):
listitems2[i].UserControlClicked+= new System.EventHandler(this.UserControl_Click);
or maybe like this (with casting)
(listitems2[i] as UserControl1).UserControlClicked+= new System.EventHandler(this.UserControl_Click);
and handle the rest in your UserControl_Click method like before

Enabling/disabling button

I am having trouble getting my 'start' button to show when I select either of the radio boxes.
Ideally, when one of the boxes is selected, the 'start' button will enable and allow to be clicked.
Here is my code for the form, as I am relatively new to C# I'm not sure if I'm posting all of the code you need, I'll post more if required.
public partial class mainForm : Form
{
public mainForm() {
InitializeComponent();
}
private void label1_Click(object sender, EventArgs e) {
}
private void mainForm_Load(object sender, EventArgs e) {
title.Font = new Font("Arial", 10, FontStyle.Bold);
}
private void startButton_Click(object sender, EventArgs e) {
if (radioDice.Checked) {
startButton.Enabled = true; //Activates 'start' button
whichDiceGameForm GameForm = new whichDiceGameForm();
GameForm.Show();
}
if (radioCard.Checked) {
startButton.Enabled = true; //Activates 'start' button
whichCardGame GameForm = new whichCardGame();
GameForm.Show();
}
}
}
[Posting for a friend.]
You have placed your enable code in the Button's Click event Handler while you should do it on your checkboxes changed.
Take this code :
if (radioDice.Checked)
{
startButton.Enabled = true;
}
to radioDice checkbox's changed event handler and this one :
if (radioCard.Checked)
{
startButton.Enabled = true; //Activates 'start' button
}
to radioCard checkbox's changed event handler .
Man, seriously?
ANSWER:
You're trying to enable DISABLED button when clicking on that button. You cannot click DISABLED button. What's more - you're duplicating your code.
Button should be always enabled. You only have two choices. Every choice enabled button. So it should be always enabled. No matter the choice. If there is something hidden and button may be disabled, then enable the button in Radio Click event.
Additional information about your code:
Now. About code duplication. Look what you're doing in startButton_Click. You have duplicated code.
You can do something like:
BaseGameForm f = null;
if(radioDice.Checked)
f = new DiceGameForm();
else
if(radioCard.Checked)
f = new CardGameForm();
f.Show();
(BaseGameForm is base form for every game)
But this is not good solution. Better solution is (somewhere in construtor):
radioDice.Tag = new DiceGameForm();
radioCard.Tag = new CardGameForm();
Then in Start button click you look for checked radio:
foreach(Control c in selectGameTypeGroupBox.Controls) //you could do this using LINQ
{
if((c is RadioButton) && ((RadioButton)c).Checked)
{
((Form)c.Tag).Show();
}
}
But this is still not good solution, because you're creating all game forms at startup and this is stupid.
So the better solution would be to keep game form class name in your radio Tag property and then create object of this class using reflection and Activator.
But this is still not the best solution. But I assume that this is one of your first applications so I won't be telling you now about separating gui from logic. If you want to know more - read on the Internet. Or just ask.

Dynamic button in asp.net - EventHandler is not fired

I created a button from code behind:
Panel dynamicPanel = new Panel();
Button dynamicButton = new Button();
dynamicButton.Text = "View";
dynamicButton.Click += new EventHandler(dynamicButton_Click);
dynamicPanel.Controls.Add(dynamicButton);
dynamicDiv.Controls.Add(dynamicPanel);
and the OnClick method:
protected void dynamicButton_Click(object sender, EventArgs e)
{
Response.Write("view button response");
string script = "alert(\"view clicked.\");";
ScriptManager.RegisterStartupScript(this, GetType(),
"ServerControlScript", script, true);
}
When I click the button, there is postback (IsPostback with Javascript alert) but the EventHandler is not fired. I can say that content that was visible on the page disappears if that is a clue.
I need to create this in a custom protected void method.
Your code looks a bit weird to me, but as for the problem "When I click the button, the method is not fired": Try renaming the method dynamicREGButton_Click() to dynamicButton_Click().
I assume you have a method dynamicButton_Click() in your code already; otherwise, you could not compile. However, the method you register via dynamicButton.Click += new EventHandler(...); is the method you call. The code you showed us doesn't match in that regard.

How to create an onClick eventHandler for a dynamically created button

Currently, I am doing a project for students' hostel and now I have to implement some search strategies about students.Here I have to create a button dynamically when the user clicks on the another server button in .aspx page and accordingly I have to create the onclick event handler for the newly created button. The code-snippet that I used is:
protected void btnsearchByName_Click(object sender, EventArgs e)
{
TextBox tbsearchByName = new TextBox();
Button btnsearchName = new Button();
tbsearchByName.Width = 250;
tbsearchByName.ID = "tbsearchByName";
tbsearchByName.Text = "Enter the full name of a student";
btnsearchName.ID = "btnsearchName";
btnsearchName.Text = "Search";
btnsearchName.Click += new EventHandler(this.btnsearchName_Click);
pnlsearchStudents.Controls.Add(tbsearchByName);
pnlsearchStudents.Controls.Add(btnsearchName);
}
protected void btnsearchName_Click(object sender, EventArgs e)
{
lblsearch.Text = "btnsearchName_Click event fired in " + DateTime.Now.ToString();
}
Here, the problem is newly created eventHandler doesnot get fired. I have gone through this site and looked several questions and answers and also gone through the page life-cycle and they all say that the dynamic button should be on Init or Pre_init, but my problem is I have to create it when another button is clicked, how can it be possible?
You need to add the click handler for the button on every postback.
you could look for the button in the search students panel on page load or try the page OnInit() method to add the handler when its created.
Also check here:
Dynamically added ASP.NET button click handler being ignored
and here:
asp.net dynamically button with event handler
and here:
asp:Button Click event not being fired
(all of which give similar suggestions)
Try this http://msdn.microsoft.com/ru-ru/library/system.web.ui.webcontrols.button.command(v=vs.90).aspx
btnsearchName.Command += new CommandEventHandler(this.btnsearchName_Click);
btnsearchName.CommandName = "Click";
You need to recreate the button and attach the event handler every time. For this, create a list of button and save it on session. On page load, go through the List and create the button every time
public Button create_button()
{
btnsearchName.ID = "btnsearchName";
btnsearchName.Text = "Search";
btnsearchName.Click += new EventHandler(this.btnsearchName_Click);
return btnsearchName;
}
public TextBox create_textbox()
{
TextBox tbsearchByName = new TextBox();
Button btnsearchName = new Button();
tbsearchByName.Width = 250;
tbsearchByName.ID = "tbsearchByName";
tbsearchByName.Text = "Enter the full name of a student";
return tbsearchByName;
}
protected void btnsearchByName_Click(object sender, EventArgs e)
{
TextBox tbsearchByName = create_textbox();
Button btnsearchName = create_button();
//add to panels
pnlsearchStudents.Controls.Add(tbsearchByName);
pnlsearchStudents.Controls.Add(btnsearchName);
//add to session
List<Button> lstbutton = Session["btn"] as List<Button>
lstbutton.add(btnsearchName);
//similarly add textbox
//again add to session
Session["btn"] = lstbutton
}
public override page_load(object sender, eventargs e)
{
//fetch from session, the lstButton and TextBox and recreate them
List<Button> lstbutton = Session["btn"] as List<Button>;
foreach(Button b in lstbutton)
pnlsearchStudents.Controls.Add(b);
//similar for textbox
}
I am not sure but may be you have to override the OnInit() method like this.
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
}
You just need to add this code on ready state of jquery code and it will work fine for the dynamic button too
$(document).ready(function(){
$('input#tbsearchByName').click(function(){
// code goes here
});
});

Button id as an event handler

I am creating 7 buttons on the fly
when i create the buttons i am trying to have an event handler than can deal with all clicks in one method via a switch. Ideally i want to pass an id with the button that indicates what was clicked, opposed to this solution of
void pdfButton_Click(object sender, EventArgs e)
{
Button b = (Button)sender;
Console.WriteLine(b.Text);
}
as all of the buttons using this event handler have the same text. I have a unique id associated witht the buttons but no idea how to send them
thanks
You can use the Name or Tag properties.
Put the ID in the Tag property on the button when you create them and then check the ID in your event handler.
Button button = new Button();
button.Tag = 1;
...
void pdfButton_Click(object sender, EventArgs e)
{
Button b = (Button)sender;
switch ((int)b.Tag)
{
...
}
}
First: Bad practice to handle several clicks in one event via switch. But however a solution would be:
Create your own control which inherits the button and ad your ID as an property. So you can access it via:
MyButton b = (MyButton)sender;
switch(b.ID) {
//Code goes here
}
If each button you add has a unique Id, why not just use the ID property of the button?
Button button = new Button();
button.ID= "Button1";
//...
void pdfButton_Click(object sender, EventArgs e)
{
Button b = (Button)sender;
switch(button.ID)
{
case "Button1":
//...
}
}

Categories