ImageButton and GridView problem - invalid postback - asp.net

I currently have a Gridview which uses a ButtonField of type image and this works.
However I want to be able to use the ConfirmButtonExtender that is part of the AjaxControlToolkit which cannot operate on a Buttonfield so I decided to place an ImageButton inside a TemplateField however whenever I click the button I recieve an Invalid postback or callback argument error.
Any advice/suggestions would be greatly appreciated. Thank you.
New template field
<asp:TemplateField>
<ItemTemplate>
<asp:ImageButton ID="ibtnDelete" ImageUrl="~/Images/cross.png" CommandArgument='<% Eval("soid") %>' CommandName="deleteSO" AlternateText="Delete" OnClick="ibtnDelete_Click" ToolTip="Delete the selected standing order" runat="server" />
</ItemTemplate>
</asp:TemplateField>
Existing GridView
<asp:GridView ID="gvStandingOrders" runat="server" DataKeyNames="soid" OnRowCommand="gvStandingOrders_RowCommand">
<Columns>
<asp:ButtonField ButtonType="Image" CommandName="editSO" ImageUrl="~/Images/page_white_paintbrush.png" Text="Edit" />
<asp:ButtonField ButtonType="Image" CommandName="deleteSO" ImageUrl="~/Images/cross.png" Text="Delete" />
<asp:BoundField DataField="Prefix" HeaderText="Prefix" />
<asp:BoundField DataField="PhoneNumber" HeaderText="Phone Number" />
<asp:BoundField DataField="Description" HeaderText="Description" />
<asp:BoundField DataField="Amount" DataFormatString="{0:C}" HeaderText="Customer Charge" />
<asp:BoundField DataField="SOCost" DataFormatString="{0:C}" HeaderText="Bureau Buy Price" />
<asp:BoundField DataField="UnitPrice" DataFormatString="{0:C}" HeaderText="TMS Buy Price" />
<asp:BoundField DataField="Frequency" HeaderText="Frequency" />
<asp:BoundField DataField="StartDate" DataFormatString="{0:dd/MM/yyyy}" HeaderText="Start Date" />
<asp:BoundField DataField="LastInvoiceDate" DataFormatString="{0:dd/MM/yyyy}" HeaderText="Last Invoice Date" />
<asp:BoundField DataField="NextInvoiceDate" DataFormatString="{0:dd/MM/yyyy}" HeaderText="Next Invoice Date" />
<asp:BoundField DataField="EndDate" DataFormatString="{0:dd/MM/yyyy}" HeaderText="End Date" />
<asp:BoundField DataField="soid" HeaderText="SO ID" />
</Columns>
</asp:GridView>
Code behind
protected void gvStandingOrders_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName.Equals("editSO"))
{
Session["SOID"] = Convert.ToInt32(gvStandingOrders.DataKeys[Convert.ToInt32(e.CommandArgument)].Value);
Response.Redirect("/Main/ClientMaintenance/StandingOrders/EditStandingOrder.aspx", true);
}
else if (e.CommandName.Equals("deleteSO"))
{
int soid = Convert.ToInt32(gvStandingOrders.DataKeys[Convert.ToInt32(e.CommandArgument)].Value);
// Header
int provisionID = Provisioning.GenerateHeader("SO", "provisioning_standingorder");
// Create Details
GlobFunctions.UpdateStoredProc("InsertStandingOrderHeader", GlobVar.ObjConnClick, new SqlParameter[]
{
new SqlParameter("#ProvisionID", provisionID),
new SqlParameter("#Client_Action", "D"),
new SqlParameter("#SOID", soid)
});
// Audit
GlobFunctions.AddToAudit(String.Format("Removing standing order : {0}", soid), Session["CustomerCode"].ToString());
}
}
protected void ibtnDelete_Click(object sender, ImageClickEventArgs e)
{
//select the row
ImageButton imageButton = (ImageButton)sender;
TableCell tableCell = (TableCell)imageButton.Parent;
GridViewRow row = (GridViewRow)tableCell.Parent;
int soid = Convert.ToInt32(gvStandingOrders.DataKeys[Convert.ToInt32(row.RowIndex)].Value);
// Header
int provisionID = Provisioning.GenerateHeader("SO", "provisioning_standingorder");
// Create Details
GlobFunctions.UpdateStoredProc("CLICK10_InsertStandingOrderHeader", GlobVar.ObjConnClick, new SqlParameter[]
{
new SqlParameter("#ProvisionID", provisionID),
new SqlParameter("#Client_Action", "D"),
new SqlParameter("#SOID", soid)
});
// Audit
GlobFunctions.AddToAudit(String.Format("Removing standing order : {0}", soid), Session["CustomerCode"].ToString());
}

CommandArgument='<% Eval("soid") %>'
should be
CommandArgument='<%# Eval("soid") %>'
Note the "<%# "

Related

How do i know which Buttons are triggered to perform specific task in Gridview

I have 2 buttons, one is called "Accept", which is used for updating of database while another is called "View", which is used for Redirecting. However, in GridView's SelectedIndexChanged, i wasnt able to Validate which buttons were click
so I have tried Using RowCommand for the "View" button and SelectedIndexChanged for "Accept" button. But RowCommand is triggering the "Accept" button in the SelectedIndexChanged event handler.
<asp:GridView ID="QgridView" AutoGenerateColumns="False"
CssClass="table table-bordered" AllowPaging="True" PageSize="6"
BackColor="White" BorderColor="Black" BorderStyle="Solid"
ForeColor="Black" GridLines="None" runat="server"
OnRowCommand="QgridView_RowCommand"
OnSelectedIndexChanged="QgridView_SelectedIndexChanged" >
<Columns>
<asp:TemplateField HeaderText="No">
<ItemTemplate>
<span>
<%#Container.DataItemIndex + 1%>
</span>
</ItemTemplate>
</asp:TemplateField>
<asp:ImageField HeaderText="Image" DataImageUrlField="coverimg" >
<ControlStyle CssClass="coverimage"/>
<ItemStyle HorizontalAlign="Center" />
</asp:ImageField>
<asp:BoundField HeaderText="Buyer" DataField="buyer" />
<asp:BoundField HeaderText="Item" DataField="item" />
<asp:BoundField HeaderText="Price offered" DataField="price" />
<asp:buttonfield buttontype="Button"
commandname="Accept"
text="Accept"/>
<asp:BoundField DataField="quoteid" HeaderText="quoteid" ItemStyle-CssClass="hiddencol" HeaderStyle-CssClass="hiddencol" >
<HeaderStyle CssClass="hiddencol"></HeaderStyle>
<ItemStyle CssClass="hiddencol"></ItemStyle>
</asp:BoundField>
<asp:BoundField DataField="id" HeaderText="id" ItemStyle-CssClass="hiddencol" HeaderStyle-CssClass="hiddencol">
<HeaderStyle CssClass="hiddencol"></HeaderStyle>
<ItemStyle CssClass="hiddencol"></ItemStyle>
</asp:BoundField>
<asp:BoundField DataField="rtype" HeaderText="rtype" ItemStyle-
CssClass="hiddencol" HeaderStyle- CssClass="hiddencol">
<HeaderStyle CssClass="hiddencol"></HeaderStyle>
<ItemStyle CssClass="hiddencol"></ItemStyle>
</asp:BoundField>
<asp:BoundField DataField="seller" HeaderText="seller" ItemStyle-
CssClass="hiddencol" HeaderStyle-CssClass="hiddencol">
<HeaderStyle CssClass="hiddencol"></HeaderStyle>
<ItemStyle CssClass="hiddencol"></ItemStyle>
</asp:BoundField>
<asp:buttonfield buttontype="Button"
commandname="View"
text="View"/>
</Columns>
</asp:GridView>
// Behind COde page
protected void QgridView_SelectedIndexChanged(object sender, EventArgs e)
{
GridViewRow row = QgridView.SelectedRow;
string seller = row.Cells[10].Text;
string item = row.Cells[4].Text;
string type = row.Cells[9].Text;
int id = Convert.ToInt32(row.Cells[8].Text);
int quoteid = Convert.ToInt32(row.Cells[7].Text);
productDAO productdao = new productDAO();
productdao.GridPush(quoteid, id)
}
protected void QgridView_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "View")
{
Response.Redirect("ListingItems.aspx");
}
}
I want the "Accept" BUtton to perform the updating of database while the "View button to perform Response.Redirect. However, RowCommand does not fire and instead, it triggers the "Accept" button in SelectedIndexChanged. May i know how can perform the different task for each button?
[Gettting row data from GridView]
protected void QgridView_RowCommand(object sender,
GridViewCommandEventArgs e)
{
System.Diagnostics.Debug.WriteLine("onrowcommand");
if (e.CommandName == "View")
{
System.Diagnostics.Debug.WriteLine("ButtonView is clicked");
Response.Redirect("ListingItems.aspx");
}
else if (e.CommandName == "Accept")
{
System.Diagnostics.Debug.WriteLine("buttonAccept is clicked");
productDAO productdao = new productDAO();
//GridViewRow row = QgridView.SelectedRow;
int index = Convert.ToInt32(e.CommandArgument);
GridViewRow row = QgridView.Rows[index];
string id = row.Cells[8].Text; //Returns me nothing
}
else
{
System.Diagnostics.Debug.WriteLine("no command name");
}
}
I think you are no need to check the rowcommand or onselected Index change event you can directly set button on click event. if you are using the inside your Gridview, then you should be able to register an event in your button code as:
<asp:Button runat="server" OnClick="YourclickEvent" />
For more details on event you should read this: https://www.codeproject.com/Articles/50540/GridView-Event-Handling
One Addition: if using row command then identify each button with command name and you can perform your task easily.
According to your code SelectedIndexChanged should be never fired (no select command).
RowCommand handler always fire first (before more specific handlers).
Look at sample working code.
.aspx
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataKeyNames="CategoryID"
DataSourceID="sqlCategory"
OnSelectedIndexChanged="GridView1_SelectedIndexChanged"
OnRowCommand="GridView1_RowCommand" AllowPaging="True">
<Columns>
<asp:CommandField ShowSelectButton="True" />
<asp:BoundField DataField="CategoryID" HeaderText="CategoryID" InsertVisible="False" ReadOnly="True" SortExpression="CategoryID" />
<asp:BoundField DataField="CategoryName" HeaderText="Category Name" SortExpression="CategoryName" />
<asp:ButtonField ButtonType="Button" CommandName="Accept" HeaderText="Accept" ShowHeader="True" Text="Accept" />
<asp:ButtonField ButtonType="Button" CommandName="View" HeaderText="View" ShowHeader="True" Text="View" />
<%-- Use HyperLinkField instead of ButtonField --%>
<asp:HyperLinkField DataNavigateUrlFields="CategoryID" DataNavigateUrlFormatString="category.aspx?categoryid={0}" DataTextField="CategoryName" DataTextFormatString="View {0}" HeaderText="Direct View" />
<asp:CommandField ButtonType="Button" ShowEditButton="True" />
</Columns>
</asp:GridView>
<%-- Data from NorthWind learning DB --%>
<asp:SqlDataSource ID="sqlCategory" runat="server" ConnectionString="<%$ ConnectionStrings:DBConnection %>"
SelectCommand="SELECT CategoryID, CategoryName FROM Categories"
UpdateCommand="update categories set categoryName=#CategoryName where CategoryID=#CategoryID">
<UpdateParameters>
<asp:Parameter Name="CategoryID" Type="Int32" />
<asp:Parameter Name="CategoryName" Type="String" />
</UpdateParameters>
</asp:SqlDataSource>
.aspx.cs
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
Trace.Write("GridView1_SelectedIndexChanged");// fired by "select" command after RowCommand finished
}
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
Trace.Write("GridView1_RowCommand");
//
if (e.CommandName == "Accept")
{
var categoryId = (int)GridView1.DataKeys[Convert.ToInt32(e.CommandArgument)].Value;//e.CommandArgument is display index
Trace.Write(e.CommandName + ": " + e.CommandArgument + " : " + categoryId.ToString());
}
else if (e.CommandName == "View")
{
Trace.Write("View " + e.CommandArgument);
}
}

When using a GridView, SelectedIndex is always 0 when using custom select button

When clicking the select button in gvSquid2, x gets a valid and correct value. When clicking the select button in gvSquid, I get an ArgumentOutOfRange Exception because gv.SelectedIndex=0. Additionally, gv.SelectedDataKey is null. How do I get the DataKey information? Putting it in a column is not acceptable, as it must be hidden from the user. Hiding the column is useless, because during DataBind(), the value is discarded. I ripped this example from Microsoft's website. What am I missing?
<asp:gridview ID="gvSquid2" DataSourceID="dsComments" AutoGenerateColumns="false" AutoGenerateSelectButton="true" DataKeyNames="ID" OnSelectedIndexChanged="gvSquid_SelectedIndexChanged" runat="server" EnableViewState="false">
<Columns>
<asp:BoundField DataField="Date" ReadOnly="true" HeaderText="Date" SortExpression="Date" />
<asp:BoundField DataField="Comment" ReadOnly="true" HeaderText="Comment" SortExpression="Comment" />
<asp:BoundField DataField="Username" ReadOnly="true" HeaderText="User" SortExpression="Username" />
</Columns>
</asp:gridview>
<asp:gridview ID="gvSquid" DataSourceID="dsComments" AutoGenerateColumns="false" DataKeyNames="ID" OnSelectedIndexChanged="gvSquid_SelectedIndexChanged" runat="server" EnableViewState="false">
<Columns>
<asp:CommandField ButtonType="Image" HeaderText="Select" ShowSelectButton="true" SelectImageUrl="~/includes/RedX.jpg" />
<asp:BoundField DataField="Date" ReadOnly="true" HeaderText="Date" SortExpression="Date" />
<asp:BoundField DataField="Comment" ReadOnly="true" HeaderText="Comment" SortExpression="Comment" />
<asp:BoundField DataField="Username" ReadOnly="true" HeaderText="User" SortExpression="Username" />
</Columns>
</asp:gridview>
protected void gvSquid_SelectedIndexChanged(object sender, EventArgs e) {
string x;
x = gvSquid.DataKeys[gvSquid.SelectedIndex].Value.ToString();
}
Try using the SelectedRow of the grid view to get to the RowIndex, like this:
protected void gvSquid_SelectedIndexChanged(object sender, EventArgs e)
{
string x;
GridViewRow theGridViewRow = gvSquid.SelectedRow;
x = gvSquid.DataKeys[theGridViewRow.RowIndex].Value.ToString();
}
I figured it out. EnableViewState="true" has to be set. Once I changed that, suddenly the DataKeys appeared.
This question helped.

Show record in gridview based on dropdown list, fromdate and enddate entered in textbox

I need to show my data in a gridview based on my dropdown list, fromdate and todate when data is entered in the textbox. How can I do that? What I have done till now is I created two pages. In first page I have a dropdown list and a form. When I select value from drop-down list the form for the selected value appears and user can enter details in it and submits that form. After submitting the data store in the database. In second page I have a grid view where stored value can be seen, dropdown list, from date and to date textbox now what I want is to show the records in the gridview based on my dropdown selection, fromdate and todate.
Code for second form:
<asp:DropDownList ID="ddlPortal" runat="server" AutoPostBack="True"
onselectedindexchanged="ddlPortal_SelectedIndexChanged">
<asp:ListItem>TRAVELONG</asp:ListItem>
<asp:ListItem>ONETRAVEL</asp:ListItem>
<asp:ListItem>.UK-BSP</asp:ListItem>
<asp:ListItem>.CA-YYZ</asp:ListItem>
<asp:ListItem>.CA-YVR</asp:ListItem>
<asp:ListItem>Partial MCO Refund</asp:ListItem>
</asp:DropDownList>
<asp:Label ID="lbFrom" Text="From" runat="server" /> <asp:TextBox ID="tbFrom" runat="server" />
<asp:Label ID="lblto" Text="To" runat="server" /> <asp:TextBox ID="tbTo" runat="server" />
<asp:Button ID="btnSearch" runat="server" Text="Search"
onclick="btnSearch_Click" />
Gridview details:
<asp:GridView ID="GridView1" runat="server" CellPadding="4" ForeColor="#333333"
GridLines="None" onrowcommand="GridView1_RowCommand"
AutoGenerateColumns="False">
<Columns>
<asp:TemplateField HeaderText="Query">
<itemtemplate>
<asp:LinkButton CommandName="cmdBind" runat="server" Text='<%#Eval("ID")%>' ID="ID" ToolTip='<%#Eval("ID")%>'>LinkButton
</asp:LinkButton>
</itemtemplate>
</asp:TemplateField>
<asp:BoundField DataField="Portal" HeaderText="Portal" />
<asp:BoundField DataField="TID" HeaderText="TID" />
<asp:BoundField DataField="PNR" HeaderText="PNR" />
<asp:BoundField DataField="TicketNumber" HeaderText="Ticket Number" />
<asp:BoundField DataField="ESACCode" HeaderText="ESACCode" />
<asp:BoundField DataField="WaiverCode" HeaderText="WaiverCode" />
<asp:BoundField DataField="Remarks" HeaderText="Remarks" />
<asp:BoundField DataField="UnusedTicketAmount" HeaderText="UnusedTicketAmount" />
<asp:BoundField DataField="ddlUnusedAmount" HeaderText="ddlUnusedAmount" />
<asp:BoundField DataField="AirlinePenality" HeaderText="AirlinePenality" />
<asp:BoundField DataField="ddlAirlinePenality" HeaderText="ddlAirlinePenality" />
<asp:BoundField DataField="NetRefundProcess" HeaderText="NetRefundProcess" />
<asp:BoundField DataField="ddlNetRefundProcess" HeaderText="ddlNetRefundProcess" />
<asp:BoundField DataField="RefundableCommission" HeaderText="RefundableCommission" />
<asp:BoundField DataField="ddlRefundableCommission" HeaderText="ddlRefundableCommission" />
<asp:BoundField DataField="CouponRefunded" HeaderText="CouponRefunded" />
<asp:BoundField DataField="RefundType" HeaderText="RefundType" />
</Columns>
I want to write code on click event of button but I don't know how. Can you help me on this?
.cs file:
protected void btnSearch_Click(object sender, EventArgs e)
{
}
If you are using DataTable for binding your GridView then, you can filter the data & bind your GridView again.
You can use: DataView.RowFilter Property for filtering data.
Eg.:
DataTable dt= GetData();
DataView dv = dt.DefaultView;
dv.RowFilter = "Portal= '" + ddlPortal.SelectedValue.Trim() + "'"
GridView1.DataSource=dv;
GridView1.DataBind();
Also, you can use LINQ to filter data:
DataTable dt= GetData();
EnumerableRowCollection<DataRow> query =
from row in dt.AsEnumerable()
where row.Field<String>("Portal") == ddlPortal.SelectedValue.Trim()
select row;
DataView dv = query.AsDataView();
GridView1.DataSource=dv;
GridView1.DataBind();

Row command event of gridview is not firing for radiobuttinlist in asp.net

I have rdiobutton list in ItemTemplet field of gridview which is set ispostback=true but still radiobutton list is not firing row_command event for gridview.If I do same for button then it works fine. I have written code to bind the grid in (!IspostBack) but still the problem is
there..How can I get the rid out of these.
This the code for my Grid.
<asp:GridView ID="grdSalesPerson" runat="server" AutoGenerateColumns="False" BackColor="#DEBA84" OnRowCommand="grdSalesPerson_RowCommand">
<Columns>
<asp:BoundField DataField="SalesPersonID" HeaderText="SalesPersonID" />
<asp:BoundField DataField="FirstName" HeaderText="First Name" />
<asp:BoundField DataField="LastName" HeaderText="Last Name" />
<asp:BoundField DataField="UserName" HeaderText="User Name" />
<asp:BoundField DataField="StateName" HeaderText="State Name" />
<asp:BoundField DataField="CityName" HeaderText="City Name" />
<asp:TemplateField HeaderText="Is Active">
<ItemTemplate>
<asp:RadioButtonList ID="rbActive" runat="server" CommandName="IsAct" AutoPostBack="true">
<asp:ListItem>Yes</asp:ListItem>
<asp:ListItem>No</asp:ListItem>
</asp:RadioButtonList>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
This is the code for Row_Command Event
protected void grdSalesPerson_RowCommand(object sender, System.Web.UI.WebControls.GridViewCommandEventArgs e)
{
if (e.CommandName == "IsAct")
{
// GridViewRow row = (GridViewRow) (((Button)grdSalesPerson.FindControl("btnIsActive")).NamingContainer);
GridViewRow row = (GridViewRow)(((RadioButton)e.CommandSource).NamingContainer);
int i = Convert.ToInt32(row.Cells[0].Text);
}
}

how to refresh the gridview after it filters (Dynamic) using LinqDataSource?

<asp:GridView ID="GridView2" runat="server" AllowPaging="True"
AllowSorting="True" AutoGenerateColumns="False" DataSourceID="LinqDataSource1">
<Columns>
<asp:BoundField DataField="UserName" HeaderText="User Name" ReadOnly="True"
SortExpression="UserName" />
<asp:BoundField DataField="FullName" HeaderText="Full Name" ReadOnly="True"
SortExpression="FullName" />
<asp:BoundField DataField="Email" HeaderText="Email" ReadOnly="True"
SortExpression="Email" />
<asp:BoundField DataField="LastLoginDate" HeaderText="Last Login" ReadOnly="True"
SortExpression="LastLoginDate" DataFormatString="{0:dd MMMM yyyy}"/>
<asp:HyperLinkField Text="Edit" DataNavigateUrlFields="UserId" DataNavigateUrlFormatString="~/Pages/UsersMaintenance/CreateEditUser.aspx?UserId={0}" />
</Columns>
</asp:GridView>
<asp:LinqDataSource ID="LinqDataSource1" runat="server" ContextTypeName="MyDataContextDataContext" onselecting="LinqDataSource_Selecting">
<WhereParameters>
<asp:Parameter Name="Subject" />
</WhereParameters>
</asp:LinqDataSource>
public void LinqDataSource1_Selecting(object sender, LinqDataSourceSelectEventArgs e)
{
this.LinqDataSource1.WhereParameters["Subject"].DefaultValue = this.txtSubject.Text;
e.Result = reporterRepo.GetInquiries();
Try using this, or modify it till it works. If I'm correct I did something like this before:
public void LinqDataSource1_Selecting(object sender, LinqDataSourceSelectEventArgs e)
{
this.LinqDataSource1.WhereParameters["Subject"].DefaultValue = this.txtSubject.Text;
GridView2.DataBind();
e.Cancel = true;
}
my gridview was in updatepanel thats why it was not refreshing the gridview
<asp:UpdatePanel....

Resources