2
Answers

how to Delete and update the Row In gridView

Imran Bashir

Imran Bashir

8y
362
1
i have one gridview the value coming from textbox when the button click then value save in gridView , i want to add the button which remove and update  the row in gridView .how do i can do this .the code of gridview is below
 
 
 
 
//this button add the grid view on button click of product details
    protected void btnSubmit0_Click(object sender, EventArgs e)
    {


        DataTable dt = new DataTable();

        dt.Columns.Add("Product");
        dt.Columns.Add("Product Name");
        dt.Columns.Add("Qunatity");
        dt.Columns.Add("UnitPrice");
        dt.Columns.Add("total");


        DataRow dr = null;
        if (ViewState["sale"] != null)
        {
            for (int i = 0; i < 1; i++)
            {
                dt = (DataTable)ViewState["sale"];
                if (dt.Rows.Count > 0)
                {
                    dr = dt.NewRow();

                    dr["Product"] = ddlProduct.SelectedValue;
                    dr["Product Name"] = ddlProduct.SelectedItem.Text;
                    dr["Qunatity"] = Convert.ToInt32(txtQuantity.Text);
                    dr["UnitPrice"] = Convert.ToInt32(TxtUnitPrice.Text);
                    dr["total"] = Convert.ToInt32(TxtTotal.Text);


                    dt.Rows.Add(dr);
                    GridView1.DataSource = dt;
                    GridView1.DataBind();

                }

            }
        }

        else
        {
            dr = dt.NewRow();

            dr["Product"] = Convert.ToInt32(ddlProduct.SelectedValue);
            dr["Product Name"] = ddlProduct.SelectedItem.Text;
            dr["Qunatity"] = Convert.ToInt32(txtQuantity.Text);
            dr["UnitPrice"] = Convert.ToInt32(TxtUnitPrice.Text);
            dr["total"] = Convert.ToInt32(TxtTotal.Text);


            dt.Rows.Add(dr);
            GridView1.DataSource = dt;
            GridView1.DataBind();

        }
        ViewState["sale"] = dt;


        lblItemAdd.Text = "item add in list";
        txtQuantity.Text = "";
        TxtUnitPrice.Text = "";
        TxtTotal.Text = "";

    }
Answers (2)
1
Vincent Maverick Durano

Vincent Maverick Durano

NA 19.1k 2.2m 8y
Hi,
Here's a step-by-step example that I wrote before that does exactly what you need.
http://www.c-sharpcorner.com/UploadFile/8c19e8/dynamically-adding-and-deleting-rows-in-gridview-and-saving/
Code is also available for download for your reference.
Accepted
1
Nishant Mittal

Nishant Mittal

NA 5.8k 354.8k 8y
Hi,
In case u will delete any row from Grid view u need to call databind again which is just refreshing the gridview to the same state that the original datasource is in.
So better is to delete the same row from your source i.e. Datatable, Dataset, DataReader etc.
Hope this will help you.