【问题标题】:How to add event on buttonfield in a datagridview如何在 datagridview 中的按钮字段上添加事件
【发布时间】:2016-06-04 13:30:06
【问题描述】:

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

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;

        }
    }

}

【问题讨论】:

    标签: c# asp.net datagridview


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      您可以使用 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

      【讨论】:

      • 感谢您的帮助,但我收到错误消息“GridView 'GridView1' 触发了未处理的事件 RowEditing。”
      猜你喜欢
      • 2012-12-18
      • 1970-01-01
      • 1970-01-01
      • 2014-12-17
      • 1970-01-01
      • 2015-12-28
      • 1970-01-01
      • 2018-01-15
      • 1970-01-01
      相关资源
      最近更新 更多