Dynamically Added Event Handler Not Firing - c#

Here is a quick code snippet, that doesn't seem to work at all for me. I'm reading from a file to create a list of radio buttons. The problem is that when one of the radio buttons is clicked the Event Handler I have set up in the code doesn't fire. I have tested it over and over in debug mode with line breaks... all with no luck. Am I missing something obvious here????
strLine = strLine.Trim();
System.Diagnostics.Debug.WriteLine("[3-a] ship by date - date: " + strLine);
try{ shipByDate = (Convert.ToDateTime(strLine)); }
catch (Exception e) { shipByDate = new DateTime(); }
shipByDesc = sr.ReadLine().Trim();
System.Diagnostics.Debug.WriteLine("[3-b] ship by date - desc: " + shipByDesc);
RadioButton button = new RadioButton();
button.Text = shipByDesc + " - " + shipByDate.ToString("MM/dd/yyyy");
button.Checked = false;
button.GroupName = "shipByOptions";
button.ID = "shipByRadio" + count;
//button.EnableViewState = true;
button.AutoPostBack = true;
button.CheckedChanged += new EventHandler(shipBy_CheckedChanged); // <-- doesn't work!!!
//form1.Controls.Add(button);
shipByPlaceHolder.Controls.Add(button);

You need to add the button on every postback before events attached to it will fire.
If you think about it for a moment, it will make sense - if the button has not been created (on the postback), then there are no button events that can fire. The button must exist before events attached to it can be fired.
The OnInit page event is the most suitable place to add dynamic controls to a page.
Read about the asp.net page life cycle.

Related

ASP.NET dynamically generated event code not running

I'm trying to fix a bug in a web application that dynamically creates buttons with events attached to them. I'm dealing with this man function that gets called from inside a for loop. From the research I've done this way of assigning the event should work, but It doesn't. In fact, on click the button disappears for some reason. Am I assigning the dynamic events wrong or could there be something else entirely going wrong? The "drivers" variable is a panel that the button is created inside.
public void generateDriver(string name, string route, string id)
{
Debug.WriteLine("A driver has been created!");
Literal driverLit = new Literal();
driverLit.Text += "<div class='routeTitle'>";
driverLit.Text += "<input type='text' id='hiddenID' text='" + id + "' hidden />";
driverLit.Text += name + "<br>";
driverLit.Text += route + "<br>";
Button newButton = new Button();
newButton.Text = "Remove";
newButton.ID = id;
newButton.Click += new EventHandler(RemoveDriver);
newButton.CssClass = "btn btn-danger";
drivers.Controls.Add(driverLit);
drivers.Controls.Add(newButton);
drivers.Controls.Add(new Literal
{
Text = "</div>"
});
}
public void RemoveDriver(object sender, EventArgs e)
{
Debug.WriteLine("An event has been triggered!");
Button removeBtn = (Button)sender;
string id = removeBtn.ID;
string querystring = Request.QueryString["id"].ToString();
List<string> routes = querystring.Split('-').ToList();
routes.Remove(id);
string newQueryString = string.Join("-", routes);
Response.Redirect("/Orders.aspx?id=" + newQueryString);
}
Thanks for any help.
You have to recreate the dynamic controls every page load, before events are handled, or the event won't have an owner. This should be done in the Initialization event (the page's OnInit event handler), prior to Load.

Why can't asp.net dynamic button fire in loop?

So I found this very puzzling problem which involves dynamic buttons.
Here is my method that creates the buttons:
private void CreateButtons()
{
//Button outside loop works
Button selectItem = new Button();
selectItem.Text = "Hello World";
selectItem.ID = "btn";
selectItem.Click += selectItem_Click;
PlaceHolder1.Controls.Add(selectItem);
int ItemCounter = 0;
for (int i = 0; i < BillDate.Count; i++)
{ //Button inside loop doesnt work
ItemCounter++;
Button selectItem = new Button();
selectItem.Text = "Hello World";
selectItem.ID = "btn-" + ItemCounter.ToString();
selectItem.Click += selectItem_Click;
PlaceHolder1.Controls.Add(selectItem);
}
}
Now here is the problem,
the button that is created outside the loop works fine (event handler selectItem_Click only redirects page).
Why does the button not work inside the loop and why does it work outside the loop?
All of the buttons in your loop have the same ID, since you're not incrementing ItemCounter. While you could just use i instead, you don't appear to be using the ID at all, so you're better off just not setting it in the first place.
Also keep in mind that on the post back the buttons need to be created and added to the page in the PreInit event in order for the event handler to be able to run.
Dynamically creating controls, particularly controls that have handlers on subsequent postbacks, can be quite tricky. It's not uncommon at all to need data from the request to be able to generate the controls, but to need the controls to be generated before the request is processed by ASP for the events to fire. It's dramatically easier to create a template that you bind your data to, using something like a GridView or a Repeater instead, as it will be able to properly handle re-creating the controls before the request is processed while still allowing you to have a dynamic number of instances of the template.
**Use the below code it will work.**
private void CreateButtons()
{
//Button outside loop works
Button selectItem = new Button();
selectItem.Text = "Hello World";
selectItem.ID = "btn";
selectItem.Click += selectItem_Click;
PlaceHolder1.Controls.Add(selectItem);
int ItemCounter = 0;
for (int i = 0; i < BillDate.Count; i++)
{ //Button inside loop doesnt work
Button selectItem = new Button();
selectItem.Text = "Hello World";
selectItem.ID = "btn-" + ItemCounter.ToString();
selectItem.Click += selectItem_Click;
ItemCounter++;
PlaceHolder1.Controls.Add(selectItem);
}
}

How to link a div Click to button click server side for dynamic controls

I've got a requirement where I need to be able to click dynamically generated div's
So,I've generated buttons also dynamically and want to link the ClickEvent of Button to div's Click event.
for (int i = 0; i < DtUsers.Rows.Count; i++)
{
ASPxButton btnButton = new ASPxButton();
btnButton.ID = "btnButton" + (i + 1);
btnButton.Visible = false;
btnButton.Click += new EventHandler(this.btnButton_Click);
btntButton.CommandArgument = DtOnlineUsers.Rows[i]["USER_ID"].ToString();
var divCustomItem = new HtmlGenericControl("div");
divUandMeUsers.Controls.Add(divCustomChatItem);
divCustomItem.Controls.Add(btnButton);
divCustomItem.Attributes.Add("onclick", "document.getElementById('<%= " + btnButton.ClientID + " %>').click()");
}
But,it is not working. Can you tell me where I've done wrong?
Is there something I need to do with the UpdatePanel AsyncPostBackTrigger?
When I click the div, in the developer tools, it is saying Uncaught TypeError: Cannot read property 'click' of null
Change
divCustomItem.Attributes.Add("onclick", "document.getElementById('<%= " + btnButton.ClientID + " %>').click()");
to
divCustomItem.Attributes.Add("onclick", "document.getElementById('" + btnButton.ClientID + "').click()");
You don't need the client side server includes during a server side operation.
Edit: OK so I've gone through your code with a finer toothed comb and I've found these additional problems:
The button's visibility is set to false so it won't even be rendered. If you want it to be clickable then you will need to hide it using css visibility.
What is an ASPxButton? Did you mean Button?
As there is nothing in the div its auto height and width will be set to zero.
Try sorting out those issues and post your new code if this still does not work.

c# how can i call click event of image button in html generic control?

I tried to call click event but it does not call it
I tried this codes: like
objImage.Click += new ImageClickEventHandler(WebForm4.ImageButtons_Click);
objImage.Click += WebForm4.ImageButtons_Click;
my codes :
public HtmlGenericControl CreateDIV_OyVerme_Sub_Yildiz(string id, int subId)
{
HtmlGenericControl objDiv = new HtmlGenericControl("div");
objDiv.ID = strControlName_DivYildiz + id + "_" + subId;
objDiv.Attributes.Add("class", strClassName_DivYildiz);
//objDiv.Attributes.Add("runat", "server");
ImageButton objImage = new ImageButton();
objImage.Attributes.Add("runat", "server");
objImage.CommandArgument = id;
//objImage.Src = strImgSrc_yildiz;
objImage.Click += new ImageClickEventHandler(WebForm4.ImageButtons_Click);
//objImage.Click += WebForm4.ImageButtons_Click;
objImage.Attributes.Add("onclick", "WebForm4.ImageButtons_Click();");
objImage.ID = strControlName_ImageYildiz + id +"_" + subId;
objImage.ImageUrl = strImgSrc_yildiz;
objImage.OnClientClick = strOnClientClickFunc_yildiz;
// objImage.Attributes.Add("OnClick","WebForm4.amethod (o;");
objImage.Style.Add(HtmlTextWriterStyle.Height, "19px");
objImage.Style.Add(HtmlTextWriterStyle.Width, "20px");
objImage.Style.Add(HtmlTextWriterStyle.BorderWidth, "0px");
objImage.Style.Add(HtmlTextWriterStyle.Position, "relative");
objImage.Style.Add(HtmlTextWriterStyle.Top, "13px");
objImage.Style.Add(HtmlTextWriterStyle.Left, "6px");
objImage.Style.Add("float", "left");
objImage.ToolTip = subId + "/" + 5;
// calling the method
// objImage.Attributes.Add("OnClientClick", "return(GetRssID(objRssItem));");
// var duck = objRssItem;
// objImage.Click += (s, e) => { WebForm4.amethod(objRssItem); };
//objImage.Click += WebForm4.amethod (objRssItem);
objDiv.Controls.Add(objImage);
return objDiv;
}
You don't need to add the attribute: onclick.
remove this line:
objImage.Attributes.Add("onclick", "WebForm4.ImageButtons_Click();");
you can simply do it like this:
ImageButton img = new ImageButton();
img.Click+=new ImageClickEventHandler(img_Click);
img.ID = "img";
img.Attributes.Add("runat","server");
form1.Controls.Add(img);
There is no issue in registering the event handler - either of below lines would register the event handler:
objImage.Click += new ImageClickEventHandler(WebForm4.ImageButtons_Click);
objImage.Click += WebForm4.ImageButtons_Click;
It's a dynamically generated image button, so for event handler to work, you need to ensure that
The image button must be re-created and added to control hierarchy on the subsequent post-back. If control is not present on post-back then it cannot raise the event.
You must ensure that the control has same ID on the post-back. Not only that it must be in the same control hierarchy and its parents also need to have same ids. The essential point is that control gets located using its ID.
The control (image button) must get added to the page's control hierarchy as early as possible - Page_Init would be the best but if that's not possible then page_load may work. Creating the control in any subsequent event would not trigger the post-back event.

Can't add programmatic controls in ASP.NET

I've got a page in ASP.NET, and I'm dynamically adding a subclass of WebControls.Button to the Controls data member of a pre-existing static TableCell. The button displays fine in the browser as expected. But when I click the button, the event handler I added for button.Click is not being called. Any suggestions as to why this is?
var controls = this.displaytable.Rows[i].Cells[j].Controls;
var button = new TableButton(j, i);
button.Click += new EventHandler(this.button_Click);
button.UseSubmitBehavior = false;
button.Text = "Available";
controls.Add(button);
Dynamically added buttons must be created on every request, most likely it is sufficient before raising postback events (e.g. OnLoad). Button needs to have an explicit ID sometime:
var controls = this.displaytable.Rows[i].Cells[j].Controls;
var button = new TableButton(j, i);
button.Click += new EventHandler(this.button_Click);
button.UseSubmitBehavior = false;
button.Text = "Available";
button.Id = string.Format("TableButton_{0}_{1}", j, i);
controls.Add(button);
This SO answer may help little bit: ASP.NET dynamic Command Button event not firing.

Categories