How to add a Onclick function to a Dynamic LinkButton? - c#

I need to add a Onclick attribute to my LinkButton which I am dynamically generating. How to add it?
Here is the code I came so far and struck with:
foreach(string i in List)//list has more than 50 data's
{
LinkButton link = new LinkButton();
link.Text = topics;
link.ID = topics;
link.Attributes.Add("runat", "server");
link.Click += new EventHandler(this.lnk_Click);
div_ID.Controls.Add(link);
div_ID.Controls.Add(new LiteralControl("<br />"));
}
public void lnk_Click(object sender,EventArgs e)
{
string ctrlId = ((Control)sender).ID;
GMethod(ctrlId); //handles some function in which i pass the id of the particular lnk button
}
I could call this lnk_Click from my LinkButton on dynamic generation. Its onclick attribute is not getting added to the link button. Please help me out on this guys. I am on urge.

You don't need to add the runat="server" attribute, as that will be done automatically. You've assigned the OnClick event handler, so you should be all set there too.
Since you're creating these controls dynamically, make sure that you have code in place to regenerate the LinkButton controls after postback, otherwise your event handler won't fire. Also make sure to assign the same IDs when regenerating it after postback.

I was also facing the same issue that the onClick event of the dynamically created hyperlink was not getting fired. I was making the mistake of placing the code of dynamic creation of hyperlink within "if(!IsPostBack)" and was assigning a random id to the hyperlink every time. So, please try assigning a unique ID and keep the code outside "if(!IsPostBack)". Will work.

Related

Dynamically added buttons wont work from the first click

i know there is a lot of questions similar to mine but none of them solved my problem.
The Idea:
i have two pages the first one is a login page and the other one is to show the logged in person attendance, in the attendance page i have two tabs one for the employee itself and the other one is to dynamically show the names of the employees under him, the second tab is presented as buttons that contain the employees name, and when you click it, it shows that person attendance.
The Problem:
when i click on the button it refresh the page without doing anything then when i click it again it works and calls the method i needed, so my question is why it doesn't work from the first click ?
Solution Attempt:
i created the buttons in code behind this way :
var button = new Button
{
ID = "Button " + a,
CommandArgument = myEmp[a].ToString(), //id of employee
Text = GetName(myEmp[a]), // name of employee
CausesValidation = false
};
button.Command += GetINAndOutManagers; //method on click
var cell = new HtmlTableCell();
var row = new HtmlTableRow();
cell.Controls.Add(button);
row.Cells.Add(cell);
myTable.Rows.Add(row); // just for organization i put them in a table
and in my html page :
<table id="myTable" runat="server" class="table table-bordered"></table>
as a place holder.
1- i have JavaScript and jquery in my page but even when i remove them it doesn't work.
2- i tried using html buttons instead in code behind put still don't work.
3- i tried putting it in page init and page preinit but no result.
the only time it worked when i put the buttons in the main page not the content page i don't know why, and i noticed when i click the button for the first time it doesn't consider it as a post back.
any ideas ?
EDIT
so to make it easier i deleted everything in my page load method
and in my page init method i have this code only.
protected void Page_Init(object sender, EventArgs e)
{
Button btn = new Button();
pnlInfo.Controls.Add(btn);
btn.ID = "Button" + 1.ToString();
btn.Text = "Test button" + 1.ToString();
btn.Click += new EventHandler(btnSubmit_click);
}
and the method on click is like this:
private void btnSubmit_click(object sender, EventArgs e)
{
System.Diagnostics.Debug.Write("**************in*****************");
}
so i only login and then it will redirect me to the second page which contains one button only created as you see in my page init method, no tabs no nothing
and in my html is this
<asp:Panel ID="pnlInfo" runat="server">
</asp:Panel>
with some css and divs that's all, and it's still won't work from the first click !
Oh Gosh, i found my solution
in my login page i used this code to transfer to my second page:
Server.Transfer("About.aspx", true);
so my buttons did not work, but when i change the code to this:
Response.Redirect("About.aspx");
everything worked !
well i'm an asp.net beginner so i don't know why that solved
my problem. but thanks everyone, hope this help someone else too.

Making a Control to be runat=server

In my application I have created a button dynamically & its name is "Dynamic_Button". Is it possible to make the button to be runat=server. I just tried the code but it doesn't work.
Dynamic_Button.Attributes.Add("runat","server");
Is there anyother ways to make it in serverside ?
When you manually instantiate a server control, there's no need to add the runat="server" attribute. This is a special attribute that's used only by the ASP.NET page parser to distinguish server controls from other markup.
The OnClick attribute in markup corresponds to the Click server-side event, which you hook up using the += operator.
So:
LinkButton lb = new LinkButton();
lb.ID = "LinkButton1";
lb.Click += click_event;
lb.Text = "testtext";
And the event handler
protected void click_event(object sender, EventArgs e)
{
}
In this example there is no need to add runat server because it already has it.
Have a look at this answer: https://stackoverflow.com/a/11337397/284240
This and this will guide you in creating and adding buttons at run time as well assigning events(client and server side).

ASP.Net ImageButton not firing onclick

I'm testing out two ImageButton controls one is set programmatically inside a GridView_RowDataBound function and the other is hard-coded on the client side as follows:
Static ImageButton (Works and fires ImageButton_Click):
<asp:ImageButton OnClick="ImageButton_Click" runat="server" ID="Foo" ImageUrl="images/edit-icon.png" />
Dynamic ImageButton (Does not work, won't fire ImageButton_Click):
protected void gv_RowDataBound(object sender, GridViewRowEventArgs e)
{
.
.
.
ImageButton i = new ImageButton();
i.ImageUrl = "/images/edit-icon.png";
i.ID = "icon_" + testID.ToString();
i.ToolTip = "Click to add a new comment";
i.Click += new ImageClickEventHandler(ImageButton_Click);
e.Row.Cells[5].Controls.Add(i);
.
.
.
}
The Dynamic ImageButton renders as follows
<input type="image" name="GridView1$ctl24$DGV1$ctl02$icon_1234" id="GridView1_ctl24_DGV1_ctl02icon_1234" title="Click to add a new comment" src="/images/edit-icon.png" onclick="ImageButton_Click;WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions("GridView1$ctl24$DGV1$ctl02$icon_1234", "", true, "", "", false, false))" style="border-width:0px;">
I notice the dynamic image button contains "onclick" vs the static imagebutton which has "OnClick", not sure if that makes a difference. I've been stumped on this for the last few hours, I don't know why the dynamic ImageButton is not firing. Please help.
UPDATE:
Thanks for all the feedback, I only need to process the ID of the ImageButton and it doesn't have to be server-side. Is there anyway I can do this from client-side using JavaScript in order to avoid postback? I tried re configuring the ImageButton as follows:
ImageButton i = new ImageButton();
i.ImageUrl = "/images/edit-icon.png";
i.ID = "icon_" + testID.ToString();
i.ToolTip = "Click to add a new comment";
i.OnClientClick = "submitComment(i.ID);return false;";
e.Row.Cells[5].Controls.Add(i);
I specify this function in the header of my web form
<head runat="server">
<script type="text/javascript">
submitComment(i.ID){
//Call WebMethod and pass comment along with this button's testID
}
</script>
</head>
But I get the following error when I click on the edit-icon ImageBtn:
Uncaught Reference Error: icon_12345 is not defined.
How is this so? If the edit-icons are already rendered and I'm just using client-side Javascript, shouldn't they already be defined and able to be properly referenced? This seems very counter intuitive to me. Am I missing something here? Is there some other control, besides and ImageButton, I can use for rendering the image without worrying about a postback, but that can still call the Javascript and pass along it's ID? What about using a regular Image control and just wiring it's onclick property to call the the submitComment function.
The problem is that on postback ASP.NET does not remember that you dynamically added a control on the previous request. The control simply does not exist in the control tree so the event will not fire.
You are asking for pain and suffering when trying to dynamically add controls. The control must be recreated by you before Page_Load if you want the event to fire. See http://forums.asp.net/t/1186195.aspx/1 for more details.
I would just hide the ImageButton for rows that don't need it.
You have to DataBind on each postback to get the control back into the ControlTree.
Maybe you could try something like this? Just make a regular img element with a data binding expression for the onclick attribute. "ID" must be a field in the gridview datasource.
<Columns>
<asp:TemplateField>
<ItemTemplate>
<img src="/images/edit-icon.png" onclick="submitComment('<%# Eval("ID", "icon_{0}") %>');"></img>
</ItemTemplate>
</asp:TemplateField>
</Columns>
Untested, but I've used something like this before. ASP.NET can get picky parsing the databinding expression.
If your page is routed, just add this code to masterpage on_load or on the page where you have the form
form1.Action = Request.Url.PathAndQuery;

Cannot access the CSS class for a link button from Code behind

Can we include a CSS class from code behind for a link button?
I have been trying this for a while, but I was not able to get it done. It does not show a hyper link nor does CSS work. Please refer to my code and see where am I doing wrong.
string link1 = "google.com"
lblclick.Text = "<p>See what our page looks like by clicking "
+ "<asp:LinkButton CssClass="+"linkclass" + ">"
+ link1 + "</asp:LinkButton>
if you want to add a linkbutton to a panel from codebehind you will have to create it from code.
LinkButton lb = new LinkButtton();
lb.cssclass="linkclass";
lb.text = "foo";
panel1.Controls.Add(lb);
Create the LinkButton in code like this:
LinkButton linkButton = new LinkButton();
linkButton.CssClass = "linkclass";
linkButton.Text = "google.com";
You can't just add ASP.NET markup as a textproperty in your code, ASP doesn't work like that. Create a Linkbutton btn = new LinkButton(), and add it: lblclick.Controls.Add(btn). Then you can edit the properties of btn as you please.
If lblclick is a Label, then you can't add a asp tag like LinkButton just like that.
If you can (or if you move the LinkButton to your markup) you need to add the runat="server" to be able to set properties like CssClass on it. If you just want a plain link you can add an anchor tag instead.
lblclick.Text = "<p>See what our page looks like by clicking
" + link1 + "</p>"
Actually, if you want a link to another page you shouldn't use LinkButton at all, but rather the HyperLink class. You can use the NavigateUrl property to set the url to open when clicking the link.
If you want to add it to your markup you do it like this
<asp:HyperLink
NavigateUrl="http://www.example.com"
CssClass="linkclass"
Text="link1"
runat="server" />
and if you want to do it dynamically in code you add it by creating it and adding it to your Controls collection.
HyperLink link = new HyperLink();
link.NavigateUrl = "http://www.example.com";
link.Text = "link1";
link.CssClass = "linkclass";
Controls.Add(link);
Just remember that when you add controls dynamically you should add it in your Page_Load event every time you load your page. If you don't want it to display set its Visible property to false and change it to true based on an event or something. Perhaps not as important when using a HyperLink, but good practice nonetheless. An example of when dynamic controls bite you if you don't is this question asked recently.

Do you HAVE to use the CommandArgument property with a LinkButton which is inside of a repeater?

The link button only sets some value as true and does nothing else.
When I run the code the LinkButton's event just won't fire!
In my aspx page I got this LinkButton inside of a repeater with CommandName="SetDefault", some ID, runat property. That's it.
In my code, inside of myRepeater_Itemcommand(), I got this
if (e.CommandName == "SetDefault")
{
Users obj = new Users();
obj.IsDefault = true;
}
[EDIT] I resolved it myself. It was a silly mistake. "l" was missing from "SetDefault" in my aspx page :/
It was a silly spelling mistake in the Command Name. I resolved it myself.

Categories