I have a Gridview, in which I have placed two LinkButtons for Edit and Delete rows.
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" OnRowCommand="GridView1_RowCommand" Width="631px" BackColor="White" BorderColor="#CCCCCC" BorderStyle="None" BorderWidth="1px" CellPadding="4" ForeColor="Black" GridLines="Horizontal" Height="144px" style="text-align: right" AllowPaging="True" OnPageIndexChanging="GridView1_PageIndexChanging">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="LinkEdit" runat="server" CommandArgument='<%#Eval("eid") %>'>Edit</asp:LinkButton>
|
<asp:LinkButton ID="LinkDelete" runat="server" CommandArgument='<%#Eval("eid") %>'>Delete</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
But when I have added pagination in that Gridview and tried to go to pages 2nd, 3rd..., it gives me the error:-
Unable to cast object of type 'System.Web.UI.WebControls.GridView' to type 'System.Web.UI.WebControls.LinkButton'.
Source Error:
Line 29: {
Line 30: string id = e.CommandArgument.ToString();
Line 31: string cmdText = ((LinkButton)e.CommandSource).Text;
Line 32: if (cmdText.Equals("Edit"))
Line 33: {
Actual Error shows in Line 31:
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
string id = e.CommandArgument.ToString();
string cmdText = ((LinkButton)e.CommandSource).Text;
if (cmdText.Equals("Edit"))
{
Response.Redirect("Emp_Edit.aspx?id=" + id);
}
else
{
Class1.EmpDelete(id);
Response.Redirect("Emp_Reg.aspx");
}
}
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
ShowAll();
}
public void ShowAll()
{
GridView1.DataSource = Class1.ShowData();
GridView1.DataBind();
}
Try like this and change everything accordingly and carefuly :
Change the View as following:
<asp:LinkButton id="LinkEdit"
Text="Edit"
CommandName="Edit"
CommandArgument='<%#Eval("eid") %>'
runat="server"/>
<asp:LinkButton id="LinkDelete"
Text="Delete"
CommandName="Edit"
CommandArgument='<%#Eval("eid") %>'
runat="server"/>
Change the CodeBehind as following:
string cmdText = e.CommandName; // Line 31
OR change your approach too as :
<asp:LinkButton id="LinkEdit"
Text="Edit"
CommandName="Edit"
CommandArgument='<%#Eval("eid") %>'
OnCommand="LinkButton_Command"
runat="server"/>
And
void LinkButton_Command(Object sender, CommandEventArgs e)
{
string cmdText = e.CommandName;
}