ASP.NET dynamically generated event code not running - c#

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.

Related

c#-adding a ASP:Button in the back code

Hi it just so happens that I have to need this kind of approach (or any suggestion if you have)
this code produce table
while (rd.Read())
{
resultsHtml.Append("<tr class='odd gradeX'>");
resultsHtml.Append("<td>" + rd["region_location"].ToString() + "</td>");
resultsHtml.Append("<td>" + rd["region_tag"].ToString() + "</td>");
resultsHtml.Append("<td class='center'>");
resultsHtml.Append("<div class='tooltip-demo'>");
resultsHtml.Append("<a class='btn btn-info' href='regionEdit.aspx?id=" + rd["region_id"].ToString() + "'><i class='fa fa-paw'></i></a> ");
resultsHtml.Append("<asp:Button ID='btnDelete' runat='server' Text='Login' CssClass='btn btn-outline btn-primary' Style='width: 100px;' OnClick='btnDelete_Click' />");
resultsHtml.Append("</div>");
resultsHtml.Append("</td>");
resultsHtml.Append("</tr>");
}
if you will notice there is an asp:button there. because i want that if the user clicks that button, it will just delete it. So I put an
public void btnSubmitDelete_Click(object sender, EventArgs e)
{
}
but the things is. It is not displaying and I can't figure out how to put the region_id in the asp:button to determine which is which to delete and every loop of the while. Please help
i think when u want to add an asp control and show that control to end user u should add dynamically control to a placeholder or panel like this code :
<asp:PlaceHolder runat="server" ID="_plchControles"></asp:PlaceHolder>
and in code bihind :
var btn = new System.Web.UI.WebControls.Button();
btn.Text = "sample";
btn.ID = "btnSubmitDelete";
btn.OnClientClick += btnSubmitDelete_Click;
_plchContent.Controls.Add(btn);
Your script will work as HTML control and you can bind click event from Javascript. To do so define a WebMethod in c# and call it from Javascript click event.
e.g.
$("#btnDelete").on("click",function(e)
{
var para=[]
para.param1=val1;
para.param2=val2;
$.post("/path/delete",para,function(result)
{
});
});
C#
[WebMethod]
public void delete(string param1,string param2)
{
//Delete code here
}
else
mohammadreza izadi answers will work if you want to asp.net control but you have to make object of button as defined not string.

how to apply CSSClass & style in while create asp button using StringBuilder in c#

My Code is below which is not working for applied css for created control at client side when applying it,
my css class is : img-rounded
string strClass = "img-rounded", strColor="Green";
StringBuilder sb = new StringBuilder();
sb.Append("<asp:Button OnClick=\"Button1_Click\" runat=\"server\" ID=\"Btn1\" CssClass=\"" + strClass + "\" BackColor=\"" + strColor + "\">" + cellData + "</asp:Button><br />");
First of all you cannot add a <asp:Button as a string to the page and expect it to work. If you want to add true asp buttons dynamically you have to take a different approach:
Button button = new Button();
button.CssClass = strClass;
button.BackColor = System.Drawing.Color.Green;
button.ID = "Btn1";
button.Text = cellData;
button.Click += new EventHandler(Button1_Click);
PlaceHolder1.Controls.Add(button);
Or you could still add a "normal" HTML button to the page, but then you have to use class= instead of CssClass=, which is an attribute of most asp controls (just as BackColor).
sb.Append("<input type=\"button\" onclick=\"Button1_Click()\" id=\"Btn1\" class=\"" + strClass + "\" value=\"" + cellData + "\"><br />");
Note that the OnClick is now a javascript call with () at the end. Of course it will not fire an event in code behind.
Manish that is not how you add an asp button, this article explains how to do it. http://www.aspsnippets.com/Articles/Dynamic-Controls-Made-Easy-in-ASP.Net.aspx
Once you create the button in the code behind then you can access all its properties including cssclass.

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.

how to access the div elements from .cs side by adding a method to ImageButton in c#

This method is in a cs class which is not in a webForm in there I create some div and classes but I want to create a method ( objImage.Attributes.Add("OnClientClick", "amethod(objRssItem)"); ) amethod is in another .cs which is in a webform. I cannot work this method when i click the imagebutton.
How can i do it? thanks
public HtmlGenericControl CreateDIV_OyVerme_Sub_Yildiz(string id, int subId, Rss.Items objRssItem)
{
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.Src = strImgSrc_yildiz;
//objImage.Click += new ImageClickEventHandler(WebForm4.ImageButtons_Click);
objImage.ID = strControlName_ImageYildiz + id +"_" + subId;;
objImage.ImageUrl = strImgSrc_yildiz;
objImage.OnClientClick = strOnClientClickFunc_yildiz;
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", "amethod(objRssItem)");
objDiv.Controls.Add(objImage);
return objDiv;
}
OnClientClick is for JavaScript. I believe you are looking to call a cs method. If you want to call a cs method then it should be clear. You use the click function of the code behind for the button. If the problem is this is a dynamic object (as you show.) Then try this
objImage.Click += myfunctiontocall;
Remember this will happen in postback and if you don't re-create the object (with the same click handler) the call of your function will not work. You need to "re-wire" it every time.
To give a parameter to an event you can wrap a closure like so.
var duck = objRssItem;
objImage.Click += (s,e) => { WebForm4.amethod (duck); };
Remember closures are a tricky business -- you are calling amethod with what has become global. Strange things can happen.

Dynamically Added Event Handler Not Firing

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.

Categories