0

enter image description here

I'm currently using ASP.net and C#. I want to add an "Edit" button to my grid view, but I don't know how can I add a command on the button. And I also would gladly welcome any suggestions on how I can enhance this 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;

        }
    }

}
Paul Roub
  • 36,322
  • 27
  • 84
  • 93
Alphi
  • 55
  • 3
  • 12

2 Answers2

0

You can use RowCommand Event in GridView. The RowCommand Event occurs when a button is clicked in a GridView control. See this

Ali Soltani
  • 9,589
  • 5
  • 30
  • 55
0

You can add a CommandField with the Edit button:

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

And process the RowEditing event:

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

More details are given here: ASP.NET GridView: How to edit and delete data records.

Community
  • 1
  • 1
ConnorsFan
  • 70,558
  • 13
  • 122
  • 146
  • thanks for the help, but im receiving an error "The GridView 'GridView1' fired event RowEditing which wasn't handled." – Alphi Jun 04 '16 at 13:49