I'm creating X linkbuttons in code behind using the following code:
HTML:
<div runat="server" id="div_tables">
</div>
Backend:
LinkButton lnkB = new LinkButton();
lnkB.ID ="LB" + row.ItemArray[1].ToString() + row.ItemArray[2].ToString();
lnkB.Text = "Link to episode";
lnkB.Attributes.Add("runat", "server");
lnkB.Click += new EventHandler(lb_Clicked);
div_tables.Controls.Add(lnkB);
OnClick method:
protected void lb_Clicked(object sender, EventArgs e)
{
LinkButton b = sender as LinkButton;
b.Text = "ASD";
}
On linkbutton click the entire page reloads instead of only the lb_Clicked method. I'm sure this is a basic linkbutton question, but I really hope someone can help me.
Thank you in advance
#
EDIT, Found this other post which gives a solution to the problem:
Can't call Click Event on dynamic button
As Mark correctly says, the data is lost at the pageload. This post suggest to use viewstate to only recreate the desired button.
The entire page will always reload. Keep in mind, after the page is served there is no page anymore. When you click a button it then transmits everything back to the server. The server then spins up the page, goes through it's events, and then processes the appropriate postback such as the linkbutton's click event.
If you want to ensure certain other code isn't run, such as code in your OnLoad, you must enclose it in an if statement such as:
if(!Page.IsPostBack)
{
// only do things the first time the page is laoded.
}
Also, when creating dynamic controls you have to re-create them each time the page posts back, and early enough in the page's lifecycle that they actually exist in time to receive a postback event. OnLoad or OnPreLoad are the latest events you should do this in (don't use Page_Load as it occurs after OnLoad and is generally too late).
For easier processing, such as if you are having the linkbutton do something with a record, you may want to look at the Command Event. This behaves as the click does, but gives you access to the CommandName and CommendArgument which you can set on the linkbutton and use to pass information such as the ID of a selected record.
Related
I have a situation where I'm not sure if I should use a HyperLink or LinkButton. When a user clicks on a list of links I want to trigger a click event where I save some information to session (should use LinkButton) but I also want these links to open up new tabs (should use HyperLink).
A LinkButton will postback, it's essentially a button that renders like a link. You could set a response.redirect(url) in the event handler to set a new tab.
Can you add more information, of what you want to do in the handler, maybe this could be achieved with Jquery calling a server-side method?
Difference between Hyperlink and LinkButton
Click Api with Jquery and Jquery post.
You will need to use a LinkButton which causes a PostBack. To open additional tabs, emit JavaScript.
protected void MyLinkButton_Click(object sender, EventArgs e)
{
Session["MyData"] = 123;
Page.ClientScript.RegisterStartupScript(Page.GetType(),
"newWindow",
"window.open('http://myurl','_blank');",
true);
}
I would say a HyperLink that hits a specific URL to store the necessary session data, then use Response.Redirect to redirect to the following page after storing the information.
The HyperLink's URL would point to your server so that you can store the information, and then you would use a redirect to point the user to the correct endpoint after storing the necessary data.
Example
HyperLink's URL points to ~/yourpage.aspx?state=NY, with target="_blank"
Server responds to URL and checks querystring.
If query string exists, store data (if (Request.QueryString["state"] != null) Session["state"] = Request.QueryString["state"])
Redirect the user to the appropriate URL (Response.Redirect("http://www.ny.gov"))
If the data is at all confidential, then you would want to use the LinkButton methods pointed out in other answers. Opening up a new tab is tricky, so you would probably have to write out some Javascript as outlined in #andleer's answer since I don't believe there is an easy way to pop open a new window from the server side otherwise.
You need to use LinkButton.
The difference between the two is that LinkButton postbacks your page to the server allowing you to make your logic while HyperLink does not postbacks - just redirects you to the specified link, therefore, use HyperLink when you want to navigate.
The LinkButton control is used to create a hyperlink button. This control looks like a HyperLink control but has the same functionality as the Button control.
with LinkButton you also get the facility of Web Control Standard Properties and Control Standard Properties .
You're right, can't do both, since a LinkButton will trigger a postback, and a hyperlink will simply navigate to a new page.
In your case use you can use a LinkButton and the server code will have to to do a redirect (if you want to navigate to another page) or handle the Tabs and return the page with the Tab opened if you are using a tabs element. (so the tab navigation will not be done front end)
In such cases you can use button for saving some information and you can also use it as a like option. But if you want to add a link then you have to use hyperlink.. You can also use javascript to link a url with the button so that when user clicks on that button the session information will get stored and then he will redirected to the new webpage.
I've tried to use LinkButton to add "Previous" "Home" and "Next" to my webpage
and once I clicked on the link, it works properly on what it does, but it changed my website's layout, take out all the available menu items on my webpage's top and left panel.
I tried to run it without assigning an event handler to the LinkButton.
When clicking on the link, my content layout doesn't change a thing, but the top and left panel changed. Weird right?
Anyone facing similar problem?
previous = new LinkButton();
next = new LinkButton();
home = new LinkButton();
previous.Text = "Previous";
previous.Click += Show_Previous;
next.Text = "Next";
next.Click += Show_Next;
home.Text = "Home";
home.Click += Show_Home;
if those link buttons are in your masterpage , in your masterpage_load event you should clear those link buttons if page ISPOSTBACK and then you should create new link buttons ! the reason that your page layout changes is that you get new linkbutton elements again and again I think !
and if those buttons are in a simple page or a content page create your linkbuttons if page is not postback and on each postback reassign the click values !
Solved it by changing LinkButton to Button. (Fast solution)
I dont get it, It works well with ImageButton and Button.
But when comes to LinkButton it changes my layouts.
Just for curiosity, anything else that works the same as LinkButton?
Can Hyperlink do the trick?
I've saw some website using c# asp to do exactly what i'm doing.
But without having the "Next"/"Previous" link text calling javascript's "_doPostBack" function. Any Idea?
i have some anchors in my aspx page.
i need to determine them (couse to run page_load) in page_load after click.
as you know those anchors are not regular asp.net controls and when you click them Page.IsPostBack is always false.
i can not use linkbuttons for some reasons.
so, how can i determine those anchors in page_load after click?
thanks in advance
Well, my only idea is tu use parameters in url and use them to identify which hyperlink was clicked.
Link 1
Link 2
And in code behind
string linkName = Request.QueryString["linkName"];
if (linkName = "link1")
{ // something
}
But what's the reason you cannot use LinkButtons or some other controls? This approach would be more convenient in ASP.NET.
A more elegant way would be to use __doPostBack function(It's already there in every asp.net page) in javascript and set appropiate
event targent and event argument. This is how asp.net controls posts back to server
for example.
<a id="LinkButton1" href="javascript:__doPostBack('Anchor1','')">LinkButton</a>
On the server Side, you could handle the click event as following
protected void Anchor1_Click(object sender, EventArgs e)
{
Response.Write("Hello World !");
}
I'm having an issue with trying to add a button to my grid. My GridView is first loaded with data in the PageLoad event.
I'm then taking the data in the first cell of each row, and creating a button that will link to a URL. To get the URL, I have to run a query with the data in the first cell as a parameter. I was doing this in the RowDataBound event at first, but hitting that query for every row was making it really slow.
So I decided to add a button that would retrieve the URL only when you clicked the button.
Here's my GridView:
<asp:GridView ID="gvResults" runat="server"
OnRowDataBound="gvResults_RowDataBound"
OnRowCommand="gvResults_RowCommand">
</asp:GridView>
And my code:
protected void gvResults_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.DataItem != null)
{
LinkButton lb = new LinkButton();
lb.CommandArgument = e.Row.Cells[0].Text;
lb.CommandName = "NumClick";
lb.Text = e.Row.Cells[0].Text;
e.Row.Cells[0].Controls.Add((Control)lb);
}
}
protected void gvResults_RowCommand(object sender, CommandEventArgs e)
{
switch (e.CommandName.ToLower())
{
case "numclick":
string url = GetUrl(e.CommandArgument.ToString());
Response.Redirect(url);
break;
default:
break;
}
}
The grid generates fine, the button gets added to the grid for each row. But when I click on it, the RowCommand event doesn't fire, and the page just refreshes.
Does anyone know what the issue is?
Why use a dynamic button at all? You can easily put the linkbutton directly into the markup of the gridview (as long as you don't mind using a template field) and there will be no need to mess around with the RowDataBound event.
Your markup would look something like the following:
<Columns>
<asp:TemplateField HeaderText="SomeHeaderText">
<ItemTemplate>
<asp:LinkButton ID="lnkBtn" runat="server" CommandName="NumClick" CommandArgument= '<%# (string)Eval("dbValue") %>' Text='<%# (string)Eval("dbValue") %>'></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField></asp:BoundField>
<asp:BoundField></asp:BoundField>
<asp:BoundField></asp:BoundField>
</Columns>
Add breakpoints to the RowCommand event and make sure that you can hit the breakpoints.
The problem may lie elsewhere.
Also, make sure that you're not databinding on postback.
You have a big trouble with your code. It's pretty hard for me to explain what's your big mistake, but I can easily tell you how to fix.
The problem is that you generate a new button inside the RowDataBound event, definitely the wrongest choice. The button gets rendered because it exists after that event when page renders, but doesn't exist before data binding. If you bind data everytime you load the page (even during postback) the button still gets rendered because you generate a new button.
But since the button doesn't exist before data binding, it cannot raise events. You must declare the button from markup into a template of GridView, then access it not by using new LinkButton() but by using e.Row.Cells[0].FindControl("buttonId") and set its text. Then, you have to set its markup in order to fire its own Command event (not RowCommand) and handle it as you used (don't forget to set CommandArgument during data binding)
[Edit] I also made a mistake: controls inside data bound controls also don't exist before data binding. But they are initialized not with new Control() (by the private methods of data bound control) but with Page.LoadControl(typeof(Control)). That's the first thing you must fix when you load controls dynamically!!
Because the control is added dynamically on databind and you have to databind the gridview for each postback, the control being "clicked" is different each time. The event doesn't fire because at the time it needs to fire it doesn't exist as it did in the last iteration of the page.
I notice you don't have any logic determine if the button should be there, and it always goes into cell[0].
You should place this button into a TemplateItem so that it exists properly. If you have a need to do it in code-behind, you are probably better served doing it in the RowCreated event.
i have save button in around 150 pages. when ever the user clicks on save button i should disable the button after the click. so that user does not keep clicking on save button again.
protected void Button1_Click(object sender, EventArgs e)
{
// right now once the user clicks the save button
Button1.Enabled = "false"
}
right now i am doing like this. is there any better solution u can provide me to improve codeing here would be great.
thank you
I think the best option to accomplish this is using javascript. If you are using jQuery (which I can even start to recommend enough) then you can put the javascript in your masterpage. You just need to find a way to create a selector for your save buttons. Like this:
$(document).ready(function(){
$('.saveButton').bind("click", function(e) {
$(this).attr("disabled", "true");
return true; //causes the client side script to run.
});
});
In this example, I assumed that all the save buttons would have the css class ".saveButton", but you can find your own way to select the button.
Cheers!
You can also try disabling it via Javascript.
You need to use JavaScript to alter the link once it's clicked to prevent future click handling, before allowing the page to proceed with the postback. A naive attempt would be,
<asp:LinkButton runat="server" id="button" OnClientClick="this.href='#'">
Click - doesn't quite work
</asp>
This successfully prevents successive clicks from triggering the postback, but it also prevents the first click from triggering the postback. A little more logic is required to make this work correctly. In the codebehind, I grab the actual postback JavaScript snippet and work it into some logic.
protected void Page_PreRender(object sender, EventArgs e)
{
button1.OnClientClick = string.Format(
"if(this.getAttribute('disabled')) return false; {0}; this.setAttribute('disabled','disabled'); return false;",
Page.ClientScript.GetPostBackEventReference(button1, null));
}
In the HTML template:
<asp:LinkButton runat="server" id="button" >
Click - does not allow multiple postbacks
</asp>
You can spruce this up with some CSS, and at that point I would advise including jQuery, so your code is more concise (due to its command chaining).
What you have to do is use some JavaScript and disable it when its clicked on the client side.
That click event fires on a postback.
Simplest way of attaching javascript to disable the button after user click would be this (in page onLoad event):
myButton.Attributes.Add("onclick", " this.disabled = true; " + ClientScript.GetPostBackEventReference(btnSave, null) + ";");
But if button is repeated on many pages, you can maybe create nested master page and put save button there, or inherit you page from class that implements this disable functionality. Also, you can "scan" for control you want to disable after click!