ASP.NET call a function in code behind with LinkButton - asp.net

I have this LinkButton here
<asp:LinkButton runat="server" ID="EditBtn" CssClass="LinkButton" Text="Edit" Width="45px" OnClientClick="Profiles_Edit" CommandName="edit" />
and I am trying to call this function in my code behind
protected void Profiles_Edit(Object sender, ListViewCommandEventArgs e)
{
//do something
}
but when I click on the button....nothing happens. My LinkButton is inside an ItemTemplate, which is inside a ListView, which is inside a ContentTemplate, which is inside a UpdatePanel....
What is wrong with the way I am calling it?
Thanks,
J

OnClientClick is for specifying the name of the JavaScript function on the client browser.
To call the server-side event, use OnClick.
Also, you may not need the CommandName attribute in this situation. It isn't clear where this LinkButton resides. If it's in a container like a ListView, you would handle it differently.

Related

Two Buttons updating one item of a listview

I have two buttons in a ListView. With a click on the first Button I want to update the ListView-Item. With a click on the second button i want to update the ListView-Item and redirect to a different page. Both Buttons have a property CommandName="Update". I wanted to solve my problem with the CommandArgument-Property and the OnItemUpdated-Event, but I do not know how to get the value of this Property in the event.
<asp:ObjectDataSource ID="ods" runat="server" SelectMethod="Select" UpdateMethod="Update">
<SelectParameters>
<asp:Parameter ..... />
</SelectParameters>
<UpdateParameters>
<asp:Parameters .... />
</UpdateParameters>
</asp:ObjectDataSource>
<asp:ListView ID="lv" runat="server" DataSourceID="ods" DataKeyNames="ID" OnItemUpdated="lv_OnItemUpdated">
<ItemTemplate>...</ItemTemplate>
<EditItemTemplate>
<asp:Button ID="btnUpdate" runat="server" CommandName="Update"/>
<asp:Button ID="btnUpdate2" runat="server" CommandName="Update"/>
</EditItemTemplate>
</asp:ListView>
And in codebehind:
protected void lv_OnItemUpdated(object sender, ListViewUpdateEventArgs e)
{
...
}
Is it possible to decide in lv_OnItemUpdated which Button the user clicked?
I don't believe there is a way to distinguish which control issued the Update command, since sender is the ListView itself.
A workaround would be for you to give one button the CommandName "Update", and the other "UpdateRedirect".
The "UpdateRedirect" button will fire the ListView_ItemCommand event, and from there you can call ListView.UpdateItem, keeping your updating logic in there, and then redirect next.
Why do you insist on using the OnItemUpdated event?
Well there are 2 to 3 ways of doing it: One is of CommandArgument as:
<asp:Button id="Button1"
Text="Sort Ascending"
CommandName="Sort"
CommandArgument="Ascending"
OnCommand="CommandBtn_Click"
runat="server"/>
<asp:Button id="Button2"
Text="Sort Descending"
CommandName="Sort"
CommandArgument="Descending"
OnCommand="CommandBtn_Click"
runat="server"/>
and than on server side you can have:
void CommandBtn_Click(Object sender, CommandEventArgs e)
{
if(e.CommandName == "Sort")
//do you work and so on
}
or you can cast the sender as button and take it ID to see, which button was it:
((Button)sender)).ID
or you can get button ID as:
String ButtonID = Request["__EVENTTARGET"];
I hope it will help you in fixing your problem.
so you can have like:
protected void lv_OnItemUpdated(object sender, ListViewUpdateEventArgs e)
{
// either use e.CommandName
// or user ((Button)sender)).ID
}
Give each button a distinct name. Have the same event handling method in your code behind handle both button click events. Then check which button called the method.
EDIT: A workaround would be to use javascript to put the name of the clicked button into a hidden field on the form BEFORE it goes server side (using a client side script). Then in your Listview you could check the value of the hidden field to see which button was clicked.
Ok, yes, the itemcommand is what you want:
The lifecycle for an update or insert triggers both their native events AND the itemcommand event. The itemCommand event will occur prior to the itemUpdating or the itemInserting events.
So, you can create a boolean variable called called "bSecondButtonClicked" for example Add the command argument to both buttons with the Commandname='UPDATE". the e.command argument can be evaluated at the itemcommand event point. There set your Boolean variable (or however you implement it) to true. Then, at the itemupdating event, trigger your code based on the bSecondButtonClicked.
You need to get into the ItemCommand event of your ListView
protected void lstvw_ItemCommand(object sender, ListViewCommandEventArgs e)
{
switch (e.CommandName)
{
case "new":
try
{
//e.CommandArgument
//e.CommandSource
// do your stuff here
}
catch (Exception ex)
{
}
break;
default:
break;
}
}

Reacting to Button commands inside a Web Usercontrol in a ASP.NET Repeater

I have an ASP.NET repeater, whose ItemTemplate is a WebUsercontrol named ProviderControl.
<asp:Repeater ID="rep" runat="server" OnItemDataBound="rep_ItemDataBound">
<ItemTemplate>
<custom:ProviderControl ID="row" runat="server" />
</ItemTemplate>
</asp:Repeater>
I am populating the custom control with data in the ItemDataBound event.
Inside the provider control I have two buttons that I want to be able to react to on the containing Page.
I know there are Commands, and Command arguments, but how would I do that?
Or is there an easier way than using Commands?
You have to handle ItemCommand event of "Repeater".
protected void Repeater1_ItemCommand(object source, RepeaterCommandEventArgs e)
{
Button btn = e.CommandSource as Button;
Response.Write(btn.ID);
}
The best way would be to provide custom events in your UserControl for each button-click event. The UserControl will raise and the page can handle them.
http://www.codeproject.com/Articles/8797/Mastering-Page-UserControl-Communication#4.3

<%# Eval("Name1.Text")%> is empty

<asp:Literal ID="Name1" runat="server">Item Name</asp:Literal>
<asp:LinkButton runat="server" EnableViewState="false" Text='<%#Eval("Name1.Text")%>' />
Why Eval() returns empty ?
Thanks.
You are able to Eval controls that were Databound. If you call Page.DataBind you can eval all controls which NamingContainer is the Page.
If you for example DataBind a Gridview, you could eval controls in GridRows.
The time you might want to pass dynamic value as command argument is when it is inside of a databound control.
If it is stand alone control you don't need to pass those values as command argument but simply access them directly inside the Click or OnCommand Event.
If the control is inside of a DataBound control you can set the Command argument in the code-behind.
You could debug it by handling the databinding event of whatever you're trying to databind and taking a look at the variable you're after in that context. Often trying to look at the variable in debug mode will make it very obvious what the problem is.
I don't think that control will be rendered in time.
Do it in code behind.
protected void Page_Init(object sender, Eventargs e)
{
lnkButtonID.Text = Name1.Text;
lnkButtonID.CommandArgument = Name1.Text;
}
In fac I would like to do this :
<asp:ImageButton runat="server" ID="addToCartIMG" OnCommand="btnAdd_Click" EnableViewState="false" CommandArgument='<%# itemId1.Value + ";" + Name1.Text %>' ImageUrl="<%$Resources:MasterPage, Image_AddToCart%>" />
where Item1 is hiddenField and Name1 a literal.
When I debug the method btnAdd_Click, the CommandEventArgs is empty.

ASP.Net repeater Item Command not getting fired

OK, I've used repeaters literally hundreds of times without problems but something has gone awry today. I have a repeater and I'm subscribing to the itemCommand event, but when my command runs, the page posts back but the event isn't fired.
To get around this I'm having to do my databinding on each postback.
My repeater looks like this:
<asp:Repeater id="MyRepeater" runat="server" onitemcommand="MyRepeater_ItemCommand">
<ItemTemplate>
<li>
<asp:Label id="Label" runat="server" />
<asp:LinkButton id="LinkButton1" runat="server" commandname="Complete" commandargument='<%# Eval("MyID") %>' text='<%# Eval("Title") %>' />
</li>
</ItemTemplate>
</asp:Repeater>
and my codebehind like this:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
SetupPage();
}
}
private void SetupPage()
{
// Do other stuff
MyRepeater.DataSource = Repository.GetStuff()
MyRepeater.DataBind();
}
protected void MyRepeater_ItemCommand(object sender, RepeaterCommandEventArgs e)
{
// Do all my stuff here
}
MyRepeater_ItemCommand is not getting called unless I comment out the if (!IsPostBack) line. Once that is commented out and the repeater is getting databound on each postback it works OK. I've done this in so many other pages but on this on it just doesn't seem to work.
Anyone else come across this behaviour or have a solution?
Most likely, you have disabled ViewState for the page.
The reason is that when you execute the postback, all the controls in the repeater are rebuild from the data in the viewstate normally. Then the object that should receive the event is identified based on the ID of the control, and the event is routed.
If you disable the viewstate, the control tree is not rebuild during postback, and therefore the control that should receive the event does not exist in memory. So the event dies.
If you really want to disable the viewstate, but still want to receive the event, I have a workaround (and it's not dirty at all). I've long been thinking about writing a blog entry about it, so if you want, I can take a bit time off my normal chores, and describe it.
Edit: The workaround is described here: http://petesdotnet.blogspot.dk/2009/08/asp.html
Remove if (!IsPostBack) as this is preventing the repeater from rebinding,
and the item command event could not find the row after postback.
I have the same problem and aside from using update panel, I have a required field validator in my modal. I found out that the LinkButtons in my repeater triggers the requiredFieldValidor event and then I added CausesValidation="false" in the LinkButtons of my repeater. Works as expected.
I have this problem in a repeater when I use ImageButton ...
I have search the net for this solution when LinkButton work, but not ImageButton ...
Then I think, LinkButton work? so i will use it :)
<asp:LinkButton CommandName="Filter" CommandArgument='<%# Eval("ID") %>' Text="" runat="server" >
<asp:image imageurl='<%#Eval("Img") %>' runat="server"/>
</asp:LinkButton>
So, the image is inside the <A> tag
have fun :)
I removed PostBackUrl property in linkbutton and ItemCommand fired. I think postback runs first.
That may be you have set Validations on your page. So set an new attribute, causevaliation = "false" to Link button. M sure it will solve the problem
I had a similar issue - turned out some discreet validation controls were firing elsewhere on the page. It only took me a day to figure it out ...
I am not positive about this, but you might have to set the CommandName and optionally CommandArgument properties for the button causing the ItemCommand event. Otherwise ASP.NET would assume that there is no button on the page, which you'd like to fire the event. You can try that.
Plus, if you're not differentiating between command names, why not use each button's Click event instead? Just subscribe to those in the repeater's ItemCreated or ItemDataBound.
Try using Page_init instead of Page_load and that should fix the problem.
Try this:
protected void Page_Load(object sender, EventArgs e)
{
SetupPage();
}
If you use nested-repeater, you should rebind your inner repe
Here Is the code you have to use in code behind..
after PageLoad event,
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Page_LoadComplete(object sender, EventArgs e)
{
// Bind Your Repeater here
rptUser();
}
now you can fire your Itemcommand..if you get Output please mark answer as right thanks
One other thing that it could be (as it just happened to me): if your databind takes place when your page is prerendered, it won't process the item command. Switch it to load or init and you'll be fine.

How can I assign a callback function to an asp:HyperlinkField?

I want people to click on a link (generated from an asp:HyperlinkField) and have it call a method on the server rather than redirect the user somewhere. Anyone know how to do this?
Thanks,
Matt
I'd use an asp:CommandField or asp:ButtonField instead and use ButtonType=Link - that will look the same as your linkfield, and then you can handle the OnRowCommand event in your grid to run your code.
Use an asp:LinkButton instead. Unless there's a particular reason you're attached to the asp:Hyperlink?
HyperLinkField is used for generating simple hyperlinks in databound controls. Instead you can use ButtonField. Or you can define your own link with TemplateField.
Here is a sample of generating link column which has a server side event :
<asp:templatefield headertext="Link Column">
<itemtemplate>
<asp:LinkButton ID="myLink"
CommandName="MyLinkCommand"
CommandArgument='<%#Bind("TableID") %>'
runat="server">My Link</asp:LinkButton>
</itemtemplate>
</asp:templatefield>
At code behind :
protected void YouGridView_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "MyLinkCommand")
{
// Do stuff
}
}
Why not use a ButtonField instead and set the ButtonType property to a Link? It will look just like a hyperlink.

Resources