MattR
MattR

Reputation: 641

Remove Row from GridView

I have a grid view on my page and I want to allow the user to add / remove items to it. How it works, and the add functionality does work albeit probably not great, is that a user selects a product from a drop down list, then clicks Add.

This creates a new row in grid with the select Product text and ID. The GridView markup is:

                            <asp:GridView runat="server" ID="grdSelectedProducts" BorderWidth="1px" CellPadding="3" CellSpacing="2" AutoGenerateColumns="False" OnRowDataBound="grdSelectedProducts_OnRowDataBound" ShowHeaderWhenEmpty="True" DataKeyNames="ProductId"
                                OnRowCommand="grdSelectedProducts_RowCommand" OnRowDeleted="grdSelectedProducts_RowDeleted" OnRowDeleting="grdSelectedProducts_RowDeleting">
                                <Columns>
                                    <asp:BoundField DataField="Product" HeaderText="Product" ReadOnly="False" />
                                    <asp:TemplateField>
                                        <ItemTemplate>
                                            <asp:LinkButton runat="server" ID="linkDelete" runat="server" CommandName="Delete" CommandArgument="<%# Container.DataItemIndex %>">Remove</asp:LinkButton>
                                        </ItemTemplate>
                                    </asp:TemplateField>
                                    <asp:BoundField DataField="ProductId" HeaderText="ProductId" ReadOnly="False" Visible="False" />
                                </Columns>
                            </asp:GridView>

The data in the grid is bound but there is no connection to a database, as it's just the information from the drop down.

The linkDelete is where I want to allow the user to remove an item, so my question is, how can I actually delete the row? I've got the RowCommand event up which I've tried to remove it, but it just doesn't seem to work correctly as the table either 1) gets rebound with the same data as before or 2) all rows are removed due to the binding of a new DataTable. I'm missing something obvious, but this type of grid is new to me.

Any example I've seen here or on Google has been around gridviews which are databound from SQL, or some other database, which seems to make the rebinding easier. However my version doesn't use that so binding again doesn't seem to work correctly.

    protected void grdSelectedProducts_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName == "Delete")
        {
            if (!string.IsNullOrEmpty(e.CommandArgument.ToString()))
            {
                int rowIndex = Convert.ToInt32(e.CommandArgument);
                grdSelectedProducts.DeleteRow(rowIndex);
                CountryDataTable = (DataTable)grdSelectedProducts.DataSource;
                DataTable table = CreateDataTable(false, string.Empty, string.Empty);
                grdSelectedProducts.DataSource = table;
                grdSelectedProducts.DataBind();
            }
        }
    }


    private DataTable CreateDataTable(bool isAddingValue, string selectedProduct, string selectedId)
    {
        // if isAddingValue is FALSE then it isn't from a button click to add a Product, it is just
        // a call to create the datatable

        DataTable dataTable = ProductDataTable;
        if (!dataTable.Columns.Contains("Product"))
        {
            dataTable.Columns.Add("Product");
            dataTable.Columns.Add("ProductId");
        }

        if (isAddingValue)
        {
            // Get the data from ViewState
            DataRow dataRow;
            dataRow = dataTable.NewRow();
            dataRow["Product"] = selectedProduct;
            dataRow["ProductId"] = selectedId;
            dataTable.Rows.Add(dataRow);
        }
        else
        {
            grdSelectedProducts.DataSource = null;
            grdSelectedProducts.DataSource = ProductDataTable;
            grdSelectedProducts.DataBind();
        }

        // Save the data back to ViewState
        ProductDataTable = dataTable;

        return dataTable;
    }

    private DataTable ProductDataTable
    {
        get {return ViewState["ProductDataTable"] as DataTable ?? new DataTable(); }
        set { ViewState["ProductDataTable"] = value; }
    }

I do have the RowDeleting & RowDeleted events but I don't have any code in it.

Upvotes: 3

Views: 13425

Answers (2)

Amarnath R Shenoy
Amarnath R Shenoy

Reputation: 5201

First thing you should note is you are deleting the row from grid not from the data table Then you again bind the data table which may not give you any change, What you should do is instead of deleting from grid delete it from datatable

Rewrite it like

      if (e.CommandName == "Delete")
        {
        if (!string.IsNullOrEmpty(e.CommandArgument.ToString()))
        {
            int rowIndex = Convert.ToInt32(e.CommandArgument);
            DataTable table = CreateDataTable(false, string.Empty, string.Empty);
            table.Rows.RemoveAt(rowIndex) 
            grdSelectedProducts.DataSource = table;
            grdSelectedProducts.DataBind();
        }
    }

If you need it to remove it from DB , DOnt forget to do that , And also note that the above code each time when u fetch the table it will give u everything from DB so you can make it global , or you can just remove from DB

Upvotes: 4

Aftab Ahmed
Aftab Ahmed

Reputation: 1737

try this code

if (e.CommandName == "Delete")
    {
        if (!string.IsNullOrEmpty(e.CommandArgument.ToString()))
        {
            int rowIndex = Convert.ToInt32(e.CommandArgument);
            grdSelectedProducts.DeleteRow(rowIndex);
            SqlCommand cmd = new SqlCommand ("Delete from table where id='"+ rowIndex )+"'",ConnectionObject);
            cmd.ExecutenonQuery();
            CountryDataTable = (DataTable)grdSelectedProducts.DataSource;
            DataTable table = CreateDataTable(false, string.Empty, string.Empty);
            grdSelectedProducts.DataSource = table;
            grdSelectedProducts.DataBind();
        }
    }

Upvotes: 2

Related Questions