如何在datagridview中的buttonfield上添加事件

时间:2016-06-04 13:30:07

标签: c# asp.net datagridview

enter image description here

我目前正在使用ASP.net和C#。我想添加"编辑"按钮到我的网格视图,但我不知道如何在按钮上添加命令。我也很乐意欢迎任何有关如何增强此gridview的建议。

protected void Page_Load(object sender, EventArgs e)
{
    if (Session["id"] == null)
    {
        Response.Redirect("~/LoginPage.aspx");
    }

    lbl_name.Text = "Welcome :: " + Session["username"];

    using (MySqlConnection con = new MySqlConnection(ConfigurationManager.ConnectionStrings["DBCon"].ConnectionString))
    {
        constructor var = new constructor();
        con.Open();
        string sql = "SELECT product_name,product_price,product_desc,product_stock FROM product_tbl";
        MySqlCommand cmd = new MySqlCommand(sql, con);
        MySqlDataReader reader1 = cmd.ExecuteReader();
        reader1.Close();

        try
        {

            MySqlDataAdapter da = new MySqlDataAdapter(cmd);
            DataSet ds = new DataSet();
            da.Fill(ds, "user_tbl");
            GridView1.DataSource = ds.Tables["user_tbl"];
            GridView1.DataBind();
        }

        catch (Exception ex)
        {
            lbl_result.Text = "ERROR>>" + ex.Message + "!";
        }

        finally
        {
            con.Close();
            sql = null;

        }
    }

}

2 个答案:

答案 0 :(得分:0)

您可以在GridView中使用RowCommand Event。在GridView控件中单击按钮时会发生RowCommand事件。 See this

答案 1 :(得分:0)

您可以使用Edit按钮添加CommandField:

<asp:GridView ID="GridView1" runat="server" OnRowEditing="GridView1_RowEditing" ...>
    <asp:CommandField ButtonType="Link" ShowEditButton="true" ShowCancelButton="true" />
    ....
</asp:GridView>

处理RowEditing事件:

protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
    GridView1.EditIndex = e.NewEditIndex;
    GridView1.DataSource = ...
    GridView1.DataBind();
}

此处提供了更多详细信息:ASP.NET GridView: How to edit and delete data records