Gridview onrowcommand on firing

763 views Asked by At

This is my grid view

<asp:GridView ID="GridView1" runat="server" 
          AutoGenerateColumns="False" 
          OnRowDeleting="GridView1_RowDeleting"
          OnRowEditing="GridView1_RowEditing"
          OnRowUpdating="GridView1_RowUpdating"
          OnRowCommand="GridView1_RowCommand">
    <Columns>
        <asp:BoundField DataField="name" HeaderText="name" />
        <asp:TemplateField>
            <ItemTemplate>
                <asp:LinkButton ID="btn1" Text="edit" runat="server" CommandArgument='<%#Eval("id") %>' CommandName="Edit" ></asp:LinkButton>
                <asp:LinkButton ID="Button1" Text="delete" runat="server" CommandArgument='<%#Eval("id") %>' CommandName="Delete" OnClientClick=' return confirm("do you want to delete")' ></asp:LinkButton>
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>

This is the function call

protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
    Response.Write(e.CommandArgument.ToString());

    if (e.CommandName == "Delete")
    {
        //Response.Write(e.CommandArgument);
        MySqlConnection conn = new MySqlConnection(connectionString);
        conn.Open();

        string query = "delete from brand where id='" + e.CommandArgument + "'";
        MySqlCommand cmd = new MySqlCommand(query,conn);

        cmd.ExecuteNonQuery();
        conn.Close();

        fillgrid();
    }
}

The onrowcommand does not get fired. Why?

2

There are 2 answers

0
Tim Schmelter On

Just guessing: because your Page_Load looks similar to this:

protected void Page_Load(Object sender, EventArgs e)
{
    DataBindGridView(); // here you load the datasource of the grid and call DataBind();
}

Do not DataBind the grid on postbacks, otherwise events aren't triggered since you overwrite changes with the values form database, so this should work then:

protected void Page_Load(Object sender, EventArgs e)
{
    if(!IsPostBack)
        DataBindGridView(); // here you load the datasource of the grid and call DataBind();
}
0
Sasidharan On

Enable viewstate:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="something.cs"
    ValidateRequest="false" Inherits="something" EnableViewState="true" %>

In the Page load event, do:

if(!IsPostback)
{
    callmethodtobindgrid();
}

Rowcommand event handler:

protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
    Response.Write(e.CommandArgument.ToString());

    if (e.CommandName == "Delete")
    {
        //Response.Write(e.CommandArgument);
        MySqlConnection conn = new MySqlConnection(connectionString);
        conn.Open();

        string query = "delete from brand where id='" + e.CommandArgument + "'";
        MySqlCommand cmd = new MySqlCommand(query, conn);
        cmd.ExecuteNonQuery();
        conn.Close();

        fillgrid();
    }
}