Two Buttons updating one item of a listview - asp.net

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;
}
}

Related

Disable Button after click in dnn

for one requirements i need to disable button after click and run server side code after disabled for this i have used below code which is called at pageload
btnGREntry.Attributes.Add("onclick", Page.ClientScript.GetPostBackEventReference(btnGREntry, "") +
";this.value='Please wait...';this.disabled = true;");
but it is giving me below error.
An unknown error occurred while processing the request on the server.
The status code returned from the server was: 0
please help me to find out a solution or suggest any other solution to disable button after click
Note: similar things are working in asp.net but i am using in *dotnetnuke version 7.0 *
You can do this in the code-behind.
ASPX
<asp:Button ID="Button1" runat="server" onclick="Button1_Click1" Text="Button" />
Code-behind
protected void Button1_Click1(object sender, EventArgs e)
{
Button a = (Button)sender;
a.Enabled = false;
}
Does the button have to remain disabled continuously or is it to return to enabled after page refresh? In the former case then handle it with both JavaScript and code behind. In the later case handle it with just JavaScript.
<asp:Button ID="Button1" runat="server" onClientClick="DisableButton();" onclick="Button1_Click1" Text="Button" />
JavaScript:
function DisableButton() {
var btn = $("#buttonID").attr("disabled", "disabled");
}

How to avoid Page_Load() on button click?

I have two buttons, preview and Save. With help of preview button user can view the data based on the format and then can save.
But when preview is clicked, one textbox attached to ajaxcontrol (Calender) becomes empty and user have to fill the date before saving. How to handle this? On preview click i get the details to show the data in layout.
<asp:TextBox ID="txtDate" ReadOnly="true" runat="server"></asp:TextBox>
<div style="float: right;">
<asp:ImageButton ID="imgcalender1" runat="server" ImageUrl="~/images/calendar.png"
ImageAlign="Bottom" />
<asp:CalendarExtender ID="ajCal" TargetControlID="txtpublishDate" PopupButtonID="imgcalender1"
runat="server">
</asp:CalendarExtender>
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" ValidationGroup="group1" runat="server" ControlToValidate="txtDate"
ForeColor="Red" Font-Bold="true" ErrorMessage="*"></asp:RequiredFieldValidator>
</div>
<asp:Button ID="btnPreview" runat="server" Text="Preview" OnClick="btnPreview_Click" />
<asp:Button ID="btnsubmit" runat="server" ValidationGroup="group1" Text="Save" OnClick="btnsubmit_Click" />
Use Page.IsPostback() in your aspx code (server-side). Like this:
private void Page_Load()
{
if (!IsPostBack)
{
// the code that only needs to run once goes here
}
}
This code will only run the first time the page is loaded and avoids stepping on user-entered changes to the form.
From what I am understanding the preview button is causing a postback and you do not want that, try this on your preview button:
<asp:button runat="server".... OnClientClick="return false;" />
similarly this also works:
YourButton.Attributes.Add("onclick", return false");
Edit:
it seems the answer to the user's question was simple change in the HTML mark up of the preview button
CausesValidation="False"
you can put your code in
Page_Init()
{
//put your code here
}
instead of
Page_Load()
{
//code
}
I had the same problem and the solution above of "CausesValidation="False"" and even adding "UseSubmitBehavior="False"" DID NOT work - it still called "Page_Load" method.
What worked for me was adding the following line up front in Page_Load method.
if (IsPostBack) return;
I am mentioning this if it helps someone (I meant to comment above but StackOverflow did not allow me to comment because I am a new user - hence a new reply).
Try adding this to the buttons properties in the aspx page.
OnClientClick="return false;"
For my the #tgolisch answer worked better, maybe it's because i'm still a rookie.
I was trying to load a simple captcha in my WebForm and end up using a Reference Type in the Page_Load event and in a Button Click event (for a code snippet).
In the end i only have to edit some things and it's done:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
var captchaText = generateCaptchaCode(5);
lblCaptcha.Text = captchaText;
}
}
protected void btnCheckCaptcha_Click(object sender, EventArgs e)
{
if (txtCaptchaCode.Text == lblCaptcha.Text)
lblMessage.Text = "Right input characters";
else
lblMessage.Text = "Error wrong characters";
}
form1.Action = Request.RawUrl;
Write this code on page load then page is not post back on button click

Calling code-behind from button - No overload for matches

I have a FormView used to edit records but when the user presses the Button, it also needs to do some back-end stuff in the code-behind. For this I need to pass the ID of the record.
Currently this is my code in the page:
<asp:LinkButton ID="savebtn" runat="server" CausesValidation="True"
CommandName="Update" Text="Save Changes"
OnClick="setProcessProgress" CommandArgument='<%# Eval("id") %>' />
And this is a stripped-down version of my code-behind:
protected void setProcessProgress(object sender, FormViewCommandEventArgs e)
{
if (e.CommandName == "Update")
ID_p = Int32.Parse((string)e.CommandArgument);
}
I'm getting the No overload for 'setProcessProgress' matches delegate 'System.EventHandler'
I tried changing the EventArgs to CommandEventArgs and it didn't work either.
If I use OnCommand instead of OnClick it just doesn't call setProcessProgress. Any ideas?
According to the MSDN Documentation on FormViewCommandEventArgs.
The ItemCommand event is raised when a button within the FormView
control is clicked. This allows you to provide an event-handling
method that performs a custom routine whenever this event occurs.
Buttons within a FormView control can also invoke some of the built-in
functionality of the control. To perform one of these operations, set
the CommandName property of a button to one of the values in the
following table.
The event is not assigned to the Button's OnClick event, it is actually assigned to the FormViews ItemCommand Event
i.e
<asp:FormView ID="FormView1" runat="server"
onitemcommand="setProcessProgress">
<asp:LinkButton ID="savebtn" runat="server" CausesValidation="True"
CommandName="Update" Text="Save Changes"
CommandArgument='<%# Eval("id") %>'
protected void setProcessProgress(object sender, EventArgs e)
{
LinkButton btn = sender as LinkButton;
if (btn.CommandName=="Update")
{
...
Response.Write("Updated");
...
}
}
Maybe you can try EventArgs e in your method.

How to call server side code on textbox key enter in ASP.NET

How do I call server side code for textbox's in asp.net when user presses enter key? Code behnid method is creating a dynamic control based upon a LINQ query from data table.
The textbox has a TextChanged event that will fire when the focus leaves the textbox. If this isn't good enough for you, your going to need to use javascript and the onkeypress event.
As there's no description of what your doing after the event, I'm not sure what to offer as sample code.
In my opinion OP want to submit data with pressing enter in the textbox, then do sth with string from textbox.
So if I understand it right here is solution to do this:
//aspx
<asp:Panel ID="pnlSubmit" runat="server" DefaultButton="btnSubmit">
<asp:TextBox runat="server" ID = "txbText"></asp:TextBox>
<asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClick="btnSubmit_Click" />
</asp:Panel>
//aspx.cs
protected void btnSubmit_Click(object sender, EventArgs e)
{
string textFromTextBox = txbText.Text;
//do sth with that string
}

Button's cause validation property is set to false but still it fires validation

I have a button in EmptyTempletField of gridview for which causevalidation property is set to false.
But when I try to add row in gridview from empty template field by clicking on that button, the button is not firing row command event. Moreover, it fires the validation. I have few validations which are grouped. But this button fires all validations irrespective of group. If I click on the button second time, then it fires the row command event. I can't understand what is happening..
Why button fires validation which it is not supposed to fire...???
It is not clear what is exaclty happening with your code. Anyway, it should be something similar to this
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="btnDeletePicture" runat="server" CommandName="YOURCOMMAND" Text="command" CausesValidation="false" />
</ItemTemplate>
</asp:TemplateField>
protected void GV_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "YOURCOMMAND")
{
//your code
}
}
And read this article about GridView.RowCommand, which is helpful
Hope this helps

Resources