ASP.NET PostBack is not hitting the correct method - c#

Consider the following ASP.NET code:
<asp:UpdatePanel runat="server" ChildrenAsTriggers="true">
<ContentTemplate>
<asp:MultiView runat="server" ID="MultiView" ActiveViewIndex="0">
<asp:View runat="server">
</asp:View>
<asp:View runat="server">
<p><img alt="Loading..." src="/global/images/ajax-mini-loader.gif" style="vertical-align: middle;" /> Loading...</p>
</asp:View>
<asp:View runat="server">
<asp:GridView runat="server" ID="WarrantyView" OnDataBound="WarrantyView_DataBound" AutoGenerateColumns="false" ItemType="WarrantySystem.Data.ServiceCompany">
<Columns>
<asp:BoundField HeaderText="Name" DataField="Name" />
<asp:BoundField HeaderText="Telephone" DataField="Telephone" />
<asp:BoundField HeaderText="Email" DataField="Email" />
<asp:BoundField HeaderText="Telephone 24/7" DataField="Telephone247" />
<asp:BoundField HeaderText="Email 24/7" DataField="Email247" />
<asp:TemplateField HeaderText="Actions">
<ItemTemplate>
<asp:Button runat="server" ID="btnEdit" CommandName="Edit" CommandArgument="<%# Item.ID %>" Text="Edit" />
<asp:Button runat="server" ID="btnDelete" CommandName="Delete" CommandArgument="<%# Item.ID %>" Text="Delete" OnCommand="btnDelete_Command"/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</asp:View>
<asp:View runat="server">
<p>Your data could no be loaded at this time.</p>
</asp:View>
</asp:MultiView>
<asp:Timer runat="server" ID="tmrLoadData" Enabled="true" Interval="1" OnTick="tmrLoadData_Tick" />
</ContentTemplate>
</asp:UpdatePanel>
When btnDelete is clicked, a postback event occurs to Page_Load, and never hits btnDelete_Command, as it should. I'm lost as to why!
EDIT: The same problem occurs with the edit button...Okay so in the example, there is no OnClick or OnCommand event, but I have just tested this...it does the same thing.
How it works:
The page loads and shows an empty view.
The timer ticks and begins loading data, and shows the data loading view.
Once the data loads, the data view shows.
When clicking edit, the page should redorect to the edit page.
When clicking delete, the page should just delete the entry.
EDIT: As per user comments (server-side code command code):
protected void btnDelete_Command(object sender, CommandEventArgs e)
{
bool result = this.mgr.DeleteServiceCompany(Int32.Parse(e.CommandArgument.ToString()));
}
protected void btnEdit_Command(object sender, CommandEventArgs e)
{
Response.Redirect("ServiceCompany.aspx?id=" + e.CommandArgument.ToString());
}

Use the RowCommand event of GridView to fire your Edit and Delete command.
Add this inside your GridView markup.
OnRowCommand="WarrantyView_RowCommand"
Also change the CommandName text
CommandName="Modify" // change the name here
CommandName="Remove" // change the name here
And inside the event
protected void WarrantyView_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Modify")
{
// your edit logic
}
if (e.CommandName == "Remove")
{
// your delete logic
}
}
I did recommend you to change the name of the CommandName property.
Change Edit to perhaps Modify
Change Delete to perhaps Remove
Reason being they are inbuilt gridview commands
NOTE: Ensure that your ViewState is enabled in all relevant places too. This will not work with ViewState disabled.

Related

How to Disable export button when click gridview edit button in asp.net

In my application i have export button when i click grid view in edit command i want to disable export button after it will enable. I disable export button in Edit command but when i click edit button it shows disable in minute seconds and after page post back it is enable how can i disable export button with or without post back when i click edit command.
my code:
<asp:UpdatePanel ID="panl1" runat="server">
<ContentTemplate>
<asp:Panel ID="pnl1" runat="server">
<asp:Button ID="btnExport" runat="server" OnClick="btnExport_Click" Text="Export" />
</asp:Panel>
</ContentTemplate>
</asp:UpdatePanel>
<triggers>
<asp:PostBackTrigger ControlID="btnExport" />
</triggers>
<asp:GridView ID="GridView2" runat="server" Width="100%" CssClass="mydatagrid" HeaderStyle-CssClass="header" RowStyle-CssClass="rows" AutoGenerateColumns="false"
EmptyDataText="No files uploaded" OnRowCommand="GridView1_RowCommand" OnRowDataBound="GridView1_RowDataBound" OnDataBound="GridView1_DataBound">
<Columns>
<asp:TemplateField HeaderText=" ">
<ItemTemplate>
<asp:ImageButton ID="Btn1" runat="server" Text="Edit" CommandName="mybutton" Width="20px" ImageUrl="~/images/page_white_edit.png" ToolTip="Edit" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Please tell me thank you.
Remove the UpdatePanel around btnExport, it makes no sense anyway since it's the only element in there and you cancel the UpdatePanel functionality by setting a PostBackTrigger to the button. Or place the GridView inside the UPdatePanel and keep the PostBackTrigger. Either way you can then just disable/enable the button on your edit commands in the GridView RowCOmmand method.
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "mybutton_edit")
{
btnExport.Enabled = false;
}
else if (e.CommandName == "mybutton_cancelEdit")
{
btnExport.Enabled = true;
}
}
PS the <Triggers> must be placed inside <asp:UpdatePanel>.

How to prevent full page postback on selectedindexchange for dropdownlist

<asp:UpdatePanel runat="server" ClientIDMode="Static" ID="TasksUpdatePanel" UpdateMode="Conditional">
<ContentTemplate>
<asp:Panel ID="pnlDropDown" runat="server" ClientIDMode="Static" CssClass="pnlDropDown">
<!-- TASK NAME -->
<asp:DropDownList ID="ddlTaskName" CssClass="chosen-select" DataSourceID="dsPopulateTaskName" AutoPostBack="true" DataValueField="Task Name" runat="server" Width="100%" Font-Size="11px" AppendDataBoundItems="true" OnSelectedIndexChanged="ddlTaskName_onSelectIndexChanged">
<asp:ListItem Text="All" Value="%"></asp:ListItem>
</asp:DropDownList>
</asp:Panel>
<asp:GridView ShowHeaderWhenEmpty="false" AlternatingRowStyle-BackColor="#EBE9E9" AutoGenerateColumns="false" OnSorting="yourTasksGV_Sorting" AllowSorting="true" ID="yourTasksGV" runat="server" ClientIDMode="Static" EmptyDataText="You currently have no tasks assigned to you" OnRowDataBound="yourTasksGV_RowDataBound" OnRowCreated="yourTasksGV_RowCreated">
<Columns>
<asp:TemplateField HeaderStyle-Width="2%">
<ItemTemplate>
<asp:ImageButton ImageUrl="~/cies.png" runat="server" ID="btnShowDepend" OnCommand="btnShowDepend_Command" CommandName="TaskDepend" CommandArgument='<%#Eval("TestIt") %>' ToolTip="Click to view Dependencies" />
</ItemTemplate>
</asp:TemplateField>
<asp:HyperLinkField HeaderStyle-Width="16%" Target="_self" DataNavigateUrlFields="Task Detail" DataTextField="Task Name" DataNavigateUrlFormatString="" HeaderText="Task Detail" SortExpression="Task Name" ItemStyle-CssClass="taskTableColumn" />
<asp:BoundField HeaderStyle-Width="10%" DataField="Workgroup" HeaderText="Workgroup" SortExpression="Workgroup" ItemStyle-CssClass="taskTableColumn" />
<asp:BoundField HeaderStyle-Width="7%" DataField="Status" HeaderText="Status" SortExpression="Status" ItemStyle-CssClass="taskTableColumn" />
</Columns>
</asp:GridView>
</ContentTemplate>
<%--<Triggers>
<asp:AsyncPostBackTrigger ControlID="ddlTaskName" EventName="onSelectIndexChanged" />
</Triggers>--%>
</asp:UpdatePanel>
Whenever the ddlTaskName_onSelectIndexChanged function is executed there is a full page postback rather than just updating the UpdatePanel
ddlTaskName_onSelectIndexChanged function:
protected void ddlTaskName_onSelectIndexChanged(object sender, EventArgs e)
{
PullData(ViewState["sortExp"].ToString(), ViewState["sortOrder"].ToString(), false); //calls a function to update the GridView
}
With the above code, the page does a full postback rather than just partial (only update the GridView) whenever the index is changed in the ddlTaskName
What code can I add/modify to ensure the full postback isn't executed and only update the GridView on index changed.
Thought... Do I need to add them in two separate UpdatePanel?
If I uncomment the triggers, I get the following error: A control with ID 'ddlTaskName' could not be found for the trigger in UpdatePanel 'TasksUpdatePanel'.
I am attaching the dropdownlist to the Gridview like this:
Is it because of this:
protected void yourTasksGV_RowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Header)
{
GridView hGrid = (GridView)sender;
GridViewRow gvrRow = new GridViewRow(0, 0, DataControlRowType.Header, DataControlRowState.Insert);
TableHeaderCell tcCellTask = new TableHeaderCell();
tcCellTask.Controls.Add(ddlTaskName);
gvrRow.Cells.Add(tcCellTask);
yourTasksGV.Controls[0].Controls.AddAt(0, gvrRow);
}
}
your code seems fine. did you try to comment out asp:Panel tab?
if you unccoment triggers, you need to put asp:UpdatePanel around gridview
As per this post it looks like your asp:Panel could be the culprit with the ClientIDMode="Static". Try changing this so it inherits.
You'd need to specify ChildrenAsTriggers="true" in your UpdatePanel tag. The error you're getting is because your dropdown doesn't physically exist in the markup, which is what a Trigger line expects to find during compliation/runtime - instead, you are adding it dynamically as a control in your RowCreated function. It might be possible to, in that same function, add a trigger to the UpdatePanel dynamically, if you wanted to try that, instead.

Invalid postback or callback argument error when button click - Beginner

I am getting the following error;
Invalid postback or callback argument. Event validation is enabled
using in configuration or <%#
Page EnableEventValidation="true" %> in a page. For security
purposes, this feature verifies that arguments to postback or callback
events originate from the server control that originally rendered
them. If the data is valid and expected, use the
ClientScriptManager.RegisterForEventValidation method in order to
register the postback or callback data for validation.
I added a columm, and added a button into it, When the button is fired the following C# code gets executed;
ASP.NET Code
<Columns>
<%-- <asp:BoundField /> Definitions here --%>
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="AddButton" runat="server"
CommandName="AddToCart"
CommandArgument="<%# ((GridViewRow) Container).RowIndex %>"
Text="Add to Cart" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
C#
protected void GridView1_RowCommand(object sender,GridViewCommandEventArgs e)
{
if (e.CommandName == "AddToCart")
{
int index = Convert.ToInt32(e.CommandArgument);
// Retrieve the row that contains the button
// from the Rows collection.
GridViewRow row = GridView1.Rows[index];
}
}
How do i get rid of this error;
I added <globalization requestEncoding="utf-8"/> but the error is still there.
`
UPDATE
<asp:GridView runat="server" ID="gdv" AutoGenerateColumns="True" OnSorting="sortRecord" AllowSorting="true" DataKeyNames="HotelName" CellPadding="4" Width="746px">
<Columns>
<%-- <asp:BoundField /> Definitions here --%>
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="AddButton" runat="server"
CommandName="AddToCart"
CommandArgument="<%# ((GridViewRow) Container).RowIndex %>"
Text="Add to Cart" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
What I usually find myself using is a buttons OnClick events instead of the GridViewRowCommand. It's easier to work with for the most part. So your ASP would look like;
<asp:GridView runat="server" ID="gdv" AutoGenerateColumns="False" OnSorting="sortRecord" AllowSorting="true" DataKeyNames="HotelName" CellPadding="4" Width="746px">
<Columns>
<%-- <asp:BoundField /> Definitions here --%>
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="AddButton" runat="server" OnClick="AddButton_Click" Text="Add to Cart" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
And your c# would look like;
protected void AddButton_Click(object sender, EventArgs e)
{
Button btn = (Button)sender;
GridViewRow row = (GridViewRow)btn.NamingContainer;
}
Now in your code behind you can do anything you need to do with that row, and you know you'll be getting the row you want.
Hope this helps!

Refresh an updatepanel on buttonclick from code-behind

I'm using a Gridview that is using datasource & databinding. When i reload the page the gridview is updated but I want it to be on the buttonclick, but it's not working for me.
The gridview inside the updatepanel:
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:UpdatePanel ID="upWall" runat="server" ChildrenAsTriggers="true" UpdateMode="conditional">
<ContentTemplate>
<asp:GridView ID="gvWallPosts" runat="server" AutoGenerateColumns = "false"
CaptionAlign="NotSet" CellPadding="5">
<Columns>
<asp:TemplateField HeaderText="Avsändare">
<ItemTemplate>
<%# GetSender((int)Eval("WallSender"))%>
<br />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Inlägg">
<ItemTemplate>
<%# Eval("Post")%>
<br />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</ContentTemplate>
</asp:UpdatePanel>
<asp:TextBox ID="txtWall" runat="server" Height="105px" TextMode="MultiLine" Width="227px"></asp:TextBox>
<br />
<asp:Button ID="btnWall" runat="server" Text="Posta" onclick="btnWall_Click" />
Code-behind:
protected void btnWall_Click(object sender, EventArgs e)
{
con.SendWallPost(con.GetId(Membership.GetUser().UserName), Convert.ToInt32(Request.QueryString["ID"]), txtWall.Text); //This method is sending the post
upWall.Update();
}
So, I want the updatepanel to be updated on the ButtonClick, I don't want to reload the whole page to see the result
Since i don't see the button btnWall, i assume that it's outside of the UpdatePanel.
But you need to define an explicit trigger if you want to allow a control outside of an UpdatePanel to trigger a postback.
Therefore you can use an AsyncPostBackTrigger:
<asp:UpdatePanel ID="upWall" runat="server" ChildrenAsTriggers="true" UpdateMode="conditional">
<ContentTemplate>
....
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="btnWall" EventName="Click" />
</Triggers>
</asp:UpdatePanel>
By default, partial-page updates are enabled in an update panel because the default value of the EnablePartialRendering property of the ScriptManager control is true.Putting the button in the update panel is suffice to give you what you need since the button acts as an asynchronus postback control inside the panel.Then just add this line( gvWallospts.Databind()) after your update.Let me know how it goes.
protected void btnWall_Click(object sender, EventArgs e)
{
con.SendWallPost(con.GetId(Membership.GetUser().UserName), Convert.ToInt32(Request.QueryString["ID"]), txtWall.Text); //This method is sending the post
//upWall.Update();
gvWallPosts.DataBind();
}
Try setting up you markup like this
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:UpdatePanel ID="upWall" runat="server" ChildrenAsTriggers="true" UpdateMode="conditional">
<ContentTemplate>
<asp:GridView ID="gvWallPosts" runat="server" AutoGenerateColumns = "false"
CaptionAlign="NotSet" CellPadding="5">
<Columns>
<asp:Templatefield>
<asp:Button ID="btnWall" runat="server" Text="Posta" command="Edit" />
</asp:TemplateField>
<asp:TemplateField HeaderText="Avsändare">
<ItemTemplate>
<%# GetSender((int)Eval("WallSender"))%>
<br />
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox Text='<%# Bind("WallSender")%>' />
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Inlägg">
<ItemTemplate>
<%# Eval("Post")%>
<br />
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox Text='<%# Bind("Post")%>'/>
</EditItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</ContentTemplate>
</asp:UpdatePanel>
In your grid Row updating event
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
con.SendWallPost(con.GetId(Membership.GetUser().UserName), Convert.ToInt32(Request.QueryString["ID"]), txtWall.Text);
gvWallPosts.DataBind();
}
Make sure that also you Binding code in page load is sandwiched by this
If(!IsPostBack)
{
}
You should either put the button inside the update panel or define an explicit trigger to update the update panel on button click event as suggested by Tim Schmelter.

Updatepanel inside usercontrol ascx file not updating gridview

I'm trying to be slick and I'm putting this user control in a div that covers the whole page.
However when I click on the search button I get a full postback.
Any ideas on how to get it to not postback and just update the gridview?
And just to be clear. The following control is in a ascx file. Which is called in a aspx page.
<%# Control Language="C#" AutoEventWireup="true" CodeFile="PropertyViewAddEntity.ascx.cs"
Inherits="UserControls_PropertyViewAddEntity" %>
<p>Search for State City County zip</p>
<asp:Panel ID="Panel1" runat="server" DefaultButton="Button2ae">
<p>
<asp:TextBox ID="TextBox1ae" runat="server" Width="500px"></asp:TextBox>
<asp:Button ID="Button2ae" runat="server" Text="Search" CausesValidation="false" />
</p>
</asp:Panel>
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:GridView ID="GridView2ae" runat="server" AutoGenerateColumns="False" DataSourceID="SqlDataSource3ae"
OnSelectedIndexChanged="GridView2ae_SelectedIndexChanged">
<Columns>
<asp:CommandField ShowSelectButton="True" />
<asp:BoundField DataField="zipcodeid" HeaderText="zipcodeid" SortExpression="zipcodeid" />
<asp:BoundField DataField="zip_code" HeaderText="zip_code" SortExpression="zip_code" />
<asp:BoundField DataField="state" HeaderText="state" SortExpression="state" />
<asp:BoundField DataField="city_alias_name" HeaderText="city_alias_name" SortExpression="city_alias_name" />
<asp:BoundField DataField="county_name" HeaderText="county_name" SortExpression="county_name" />
</Columns>
</asp:GridView>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="Button2ae" EventName="Click" />
</Triggers>
</asp:UpdatePanel>
btw the control is in a placeholder
<asp:PlaceHolder ID="ControlContainer" runat="server"/>
and called from the code behind.
Control mycontrol = LoadControl("~/UserControls/PropertyViewAddEntity.ascx");
ControlContainer.Controls.Add(mycontrol);
I have finally figured out the issue.
In order for things to work properly adding the user control via codebehind will not work!
To get things working properly you must declare the usercontrol on the page so that you can access the UpdateMode="Conditional" property of the usercontrol.
<%# Register TagPrefix="my" TagName="AddEntity" Src="~/UserControls/PropertyViewAddEntity.ascx" %>
<my:AddEntity Visible="false" ID="test1" runat="server" ClientIDMode="Inherit" UpdateMode="Conditional" />
I set the Visible property of the control to false so that I can show it via button click.
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
And in the code behind I did this.
protected void Button1_Click(object sender, EventArgs e)
{
test1.Visible = true;
}
Once the updatemode is set. Everything works as it should.

Categories