关于触发的Gridview rowcommand

时间:2013-09-04 09:03:59

标签: asp.net gridview rowcommand

这是我的网格视图

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

这是函数调用

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

onrowcommand不会被解雇。为什么?

2 个答案:

答案 0 :(得分:0)

猜猜:因为你的Page_Load看起来与此相似:

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

在回发时不要DataBind网格,否则事件不会被触发,因为您使用数据库的值覆盖更改,因此这应该有效:

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

答案 1 :(得分:0)

启用viewstate:

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

Page load事件中,请执行:

if(!IsPostback)
{
    callmethodtobindgrid();
}

Rowcommand事件处理程序:

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