简体   繁体   中英

How to delete a row in dynamic Gridview?

I am working, as a test project, for a simple Inventory System in ASP.NET. In one page, I have to make the page for entering Purchase details! I used the dynamic gridview to ease the data entry. I have used this tutorial and this article but I am having problem in deleting the row in the gridview. I have seen this similar post but it was not helpful.

The aspx code is as below -

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<h2>
    Purchase Management</h2>
<asp:GridView ID="PurchaseMgmtGridView" runat="server" ShowFooter="True" AutoGenerateColumns="False"
    CellPadding="4" ForeColor="#333333" GridLines="None" OnRowDeleting="PurchaseMgmtGridView_RowDeleting">
    <Columns>
        <asp:TemplateField HeaderText="Item">
            <ItemTemplate>
                <asp:DropDownList ID="ItemDropDownList" runat="server" AppendDataBoundItems="true"> 
                </asp:DropDownList>
            </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="ItemUnit">
            <ItemTemplate>
                <asp:DropDownList ID="ItemUnitDropDownList" runat="server" AppendDataBoundItems="true">
                </asp:DropDownList>
            </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Rate">
            <ItemTemplate>
                <asp:TextBox ID="RateTextBox" runat="server">
                </asp:TextBox>
            </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Qty.">
            <ItemTemplate>
                <asp:TextBox ID="QtyTextBox" runat="server">
                </asp:TextBox>
            </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Total">
            <ItemTemplate>
                <asp:Label ID="TotalLabel" runat="server">
                </asp:Label>
            </ItemTemplate>
            <FooterStyle HorizontalAlign="Right" />
            <FooterTemplate>
                <asp:Button ID="ButtonAddNewRow" runat="server" Text=" + " OnClick="ButtonAddNewRow_Click" />
            </FooterTemplate>
        </asp:TemplateField>
        <asp:CommandField ShowDeleteButton="True" />
    </Columns>
</asp:GridView>
</asp:Content>

And here is the aspx.cs Codes -

namespace SmoothInventoryWeb.Pages.ItemManagment
{
   public class Item
    {
        public string Id { get; set; }
        public string Name{get; set;}
    }

    public class ItemUnit
    {
        public string Id { get; set; }
        public string Name{get; set;}
    }
    public partial class PurchaseManagementPage : System.Web.UI.Page
    {
      public List<Item> GetItemList()
    {
        List<Item> itemList = new List<Item>();

        itemList.Add(new Item { Id = "1", Name = "Carpet" });
        itemList.Add(new Item { Id = "2", Name = "Pasmina Muffler" });
        itemList.Add(new Item { Id = "3", Name = "Large Carpet" });
        return itemList;
    }

    public List<ItemUnit> GetItemUnitList()
    {
        List<ItemUnit> itemUnitList = new List<ItemUnit>();

        itemUnitList.Add(new ItemUnit { Id = "1", Name = "Pieces" });
        itemUnitList.Add(new ItemUnit { Id = "2", Name = "Dorzen" });
        itemUnitList.Add(new ItemUnit { Id = "3", Name = "Gross" });
        return itemUnitList;
    }

    List<Item> itemList = new List<Item>();
    List<ItemUnit> itemUnitList = new List<ItemUnit>();
    protected void Page_Load(object sender, EventArgs e)
    {
        this.itemList = GetItemList();
        this.itemUnitList = GetItemUnitList();
        if (!Page.IsPostBack)
            addFirstRowInGridView();
    }

    private void FillItemDropDownList(DropDownList dropDownList)
    {
        if (dropDownList == null)
            return;
        foreach (Item item in itemList)
        {
            dropDownList.Items.Add(new ListItem(item.Name.ToString(), item.Id.ToString()));
        }
    }

    private void FillItemUnitDropDownList(DropDownList dropDownList)
    {
        if (dropDownList == null)
            return;
        foreach (ItemUnit itemUnit in itemUnitList)
        {
            dropDownList.Items.Add(new ListItem(itemUnit.Name.ToString(), itemUnit.Id.ToString()));
        }
    }


    protected void ButtonAddNewRow_Click(object sender, EventArgs e)
    {
        AddNewRow();
    }

    private void addFirstRowInGridView()
    {
        DataTable dataTable = new DataTable();
        dataTable.Columns.Add(new DataColumn("Item", typeof(string)));
        dataTable.Columns.Add(new DataColumn("ItemUnit", typeof(string)));
        dataTable.Columns.Add(new DataColumn("Rate", typeof(string)));
        dataTable.Columns.Add(new DataColumn("Qty", typeof(string)));
        dataTable.Columns.Add(new DataColumn("Total", typeof(string)));
        DataRow dataRow = dataTable.NewRow();


        dataRow["Item"] = string.Empty;
        dataRow["ItemUnit"] = string.Empty;
        dataRow["Rate"] = string.Empty;
        dataRow["Qty"] = string.Empty;
        dataRow["Total"] = string.Empty;
        dataTable.Rows.Add(dataRow);
        ViewState["CurrentTable"] = dataTable;

        PurchaseMgmtGridView.DataSource = dataTable;
        PurchaseMgmtGridView.DataBind();

        DropDownList itemDropDownList =
                      (DropDownList)PurchaseMgmtGridView.Rows[0].Cells[0].FindControl("ItemDropDownList");
        DropDownList itemUnitDropDownList =
          (DropDownList)PurchaseMgmtGridView.Rows[0].Cells[1].FindControl("ItemUnitDropDownList");
        FillItemDropDownList(itemDropDownList);
        FillItemUnitDropDownList(itemUnitDropDownList);


    }

    private void AddNewRow()
    {
        int rowIndex = 0;

        if (ViewState["CurrentTable"] != null)
        {
            DataTable dtCurrentTable = (DataTable)ViewState["CurrentTable"];
            DataRow drCurrentRow = null;
            if (dtCurrentTable.Rows.Count > 0)
            {
                for (int i = 1; i <= dtCurrentTable.Rows.Count; i++)
                {
                    DropDownList itemDropDownList =
                      (DropDownList)PurchaseMgmtGridView.Rows[rowIndex].Cells[0].FindControl("ItemDropDownList");
                    DropDownList itemUnitDropDownList =
                      (DropDownList)PurchaseMgmtGridView.Rows[rowIndex].Cells[1].FindControl("ItemUnitDropDownList");
                    TextBox rateTextBox =
                      (TextBox)PurchaseMgmtGridView.Rows[rowIndex].Cells[2].FindControl("RateTextBox");
                    TextBox qtyTextBox =
                      (TextBox)PurchaseMgmtGridView.Rows[rowIndex].Cells[3].FindControl("QtyTextBox");
                    Label totalLabel =
                      (Label)PurchaseMgmtGridView.Rows[rowIndex].Cells[4].FindControl("TotalLabel");

                    drCurrentRow = dtCurrentTable.NewRow();


                    dtCurrentTable.Rows[i - 1]["Item"] = itemDropDownList.SelectedItem.ToString();
                    dtCurrentTable.Rows[i - 1]["ItemUnit"] = itemUnitDropDownList.SelectedItem.ToString();
                    dtCurrentTable.Rows[i - 1]["Rate"] = rateTextBox.Text;
                    dtCurrentTable.Rows[i - 1]["Qty"] = qtyTextBox.Text;
                    dtCurrentTable.Rows[i - 1]["Total"] = totalLabel.Text;

                }
                dtCurrentTable.Rows.Add(drCurrentRow);
                ViewState["CurrentTable"] = dtCurrentTable;

                PurchaseMgmtGridView.DataSource = dtCurrentTable;
                PurchaseMgmtGridView.DataBind();
            }
        }
        else
        {
            Response.Write("ViewState is null");
        }
        SetPreviousData();
    }

    private void SetPreviousData()
    {
        int rowIndex = 0;
        if (ViewState["CurrentTable"] != null)
        {
            DataTable dt = (DataTable)ViewState["CurrentTable"];
            if (dt.Rows.Count > 0)
            {
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    DropDownList itemDropDownList =
                      (DropDownList)PurchaseMgmtGridView.Rows[rowIndex].Cells[0].FindControl("ItemDropDownList");
                    DropDownList itemUnitDropDownList =
                      (DropDownList)PurchaseMgmtGridView.Rows[rowIndex].Cells[1].FindControl("ItemUnitDropDownList");
                    TextBox rateTextBox =
                      (TextBox)PurchaseMgmtGridView.Rows[rowIndex].Cells[2].FindControl("RateTextBox");
                    TextBox qtyTextBox =
                      (TextBox)PurchaseMgmtGridView.Rows[rowIndex].Cells[3].FindControl("QtyTextBox");
                    Label totalLabel =
                      (Label)PurchaseMgmtGridView.Rows[rowIndex].Cells[4].FindControl("TotalLabel");

                    FillItemDropDownList(itemDropDownList);
                    FillItemUnitDropDownList(itemUnitDropDownList);


                    if (i < dt.Rows.Count - 1)
                    {
                        //itemDropDownList.SelectedValue = dt.Rows[i]["Item"].ToString();
                        //itemUnitDropDownList.SelectedValue = dt.Rows[i]["ItemUnit"].ToString();
                        itemDropDownList.ClearSelection();
                        itemDropDownList.Items.FindByText(dt.Rows[i]["Item"].ToString()).Selected = true;
                        itemUnitDropDownList.ClearSelection();
                        itemUnitDropDownList.Items.FindByText(dt.Rows[i]["ItemUnit"].ToString()).Selected = true;
                    }

                    rateTextBox.Text = dt.Rows[i]["Rate"].ToString();
                    qtyTextBox.Text = dt.Rows[i]["Qty"].ToString();
                    totalLabel.Text = dt.Rows[i]["Total"].ToString();
                    rowIndex++;
                }
            }
        }
    }

    protected void PurchaseMgmtGridView_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        SetRowData();
        if (ViewState["CurrentTable"] != null)
        {
            DataTable dt = (DataTable)ViewState["CurrentTable"];
            DataRow drCurrentRow = null;
            int rowIndex = Convert.ToInt32(e.RowIndex);
            if (dt.Rows.Count > 1)
            {
                dt.Rows.Remove(dt.Rows[rowIndex]);
                drCurrentRow = dt.NewRow();
                ViewState["CurrentTable"] = dt;
                PurchaseMgmtGridView.DataSource = dt;
                PurchaseMgmtGridView.DataBind();

                for (int i = 0; i < PurchaseMgmtGridView.Rows.Count - 1; i++)
                {
                    PurchaseMgmtGridView.Rows[i].Cells[0].Text = Convert.ToString(i + 1);
                }
                SetPreviousData();
            }
        }
    }
    private void SetRowData()
    {
        int rowIndex = 0;

        if (ViewState["CurrentTable"] != null)
        {
            DataTable dtCurrentTable = (DataTable)ViewState["CurrentTable"];
            DataRow drCurrentRow = null;
            if (dtCurrentTable.Rows.Count > 0)
            {
                for (int i = 1; i <= dtCurrentTable.Rows.Count; i++)
                {
                    DropDownList itemUnitDropDownList =
                      (DropDownList)PurchaseMgmtGridView.Rows[rowIndex].Cells[1].FindControl("ItemUnitDropDownList");
                    DropDownList itemDropDownList =
                       (DropDownList)PurchaseMgmtGridView.Rows[rowIndex].Cells[0].FindControl("ItemDropDownList");

                    TextBox rateTextBox =
                      (TextBox)PurchaseMgmtGridView.Rows[rowIndex].Cells[2].FindControl("RateTextBox");
                    TextBox qtyTextBox =
                      (TextBox)PurchaseMgmtGridView.Rows[rowIndex].Cells[3].FindControl("QtyTextBox");
                    Label totalLabel =
                      (Label)PurchaseMgmtGridView.Rows[rowIndex].Cells[4].FindControl("TotalLabel");
                    drCurrentRow = dtCurrentTable.NewRow();
                    //drCurrentRow["RowNumber"] = i + 1;
                    dtCurrentTable.Rows[i - 1]["Item"] = itemDropDownList.SelectedItem.ToString();
                    dtCurrentTable.Rows[i - 1]["ItemUnit"] = itemUnitDropDownList.SelectedItem.ToString();
                    dtCurrentTable.Rows[i - 1]["Rate"] = rateTextBox.Text;
                    dtCurrentTable.Rows[i - 1]["Qty"] = qtyTextBox.Text;
                    dtCurrentTable.Rows[i - 1]["Total"] = totalLabel.Text;
                    rowIndex++;
                }

                ViewState["CurrentTable"] = dtCurrentTable;

            }
        }
        else
        {
            Response.Write("ViewState is null");
        }
     }
   }
}

These codes result something like this

在此输入图像描述

But, as soon as I start to delete one of the rows, it gives me this exception -

在此输入图像描述

This exception is thrown from the SetPreviousData() method from the following code -

DropDownList itemDropDownList =  (DropDownList)PurchaseMgmtGridView.Rows[rowIndex].Cells[0].FindControl("ItemDropDownList");

Any idea where I got wrong?

PS : Code Updated I [supplied the codes for the list of entities ieItem and ItemUnit]

It doesn't look like it's actually the deleting of the row in the GridView that's the issue, but rather something else.

First, two things to note - I can't compile because I don't have the definitions for Item and ItemUnit , so I'm doing this by reading the code. Second, I haven't finished my coffee yet! (Update: My coffee is done!)

It looks like the reference to itemDropDownList in SetPreviousData() is null, so look into why that is. It might be easier to use a foreach loop to iterate through the rows of that DataTable to avoid any issues with 0-based indexes and count-1 comparisons, etc. (Update: It still would be easier, but it's not causing the issue.)

Also, not sure if you mean to do this, but the FindControl statement to get the ItemDropDownList is using rowIndex which is always equal to i . (Update: Again, could help just to clean up the code, but it's not a requirement.)

Start by figuring out what i is when it crashes and seeing if that's what you expect and figure out why the FindControl statement isn't working properly. If it's a 0, it may be trying to reading a header row or something where that Dropdown doesn't exist.

Sorry I can't give you a definitive solution, but hopefully this helps.

Solution: After getting the full code, it was easier to see what happened. Basically, the PurchaseMgmtGridView_RowDeleting method was deleting the DropdownList from the GridView and then SetPreviousData() was trying to read something that didn't exist. The FindControl statement in SetPreviousData was returning NULL as indicated in the error message, but not for the reason I speculated earlier.

Remove the offending lines from the PurchaseMgmtGridView_RowDeleting method and you'll be all set.

  protected void PurchaseMgmtGridView_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            SetRowData();
            if (ViewState["CurrentTable"] != null)
            {
                DataTable dt = (DataTable)ViewState["CurrentTable"];
                DataRow drCurrentRow = null;
                int rowIndex = Convert.ToInt32(e.RowIndex);
                if (dt.Rows.Count > 1)
                {
                    dt.Rows.Remove(dt.Rows[rowIndex]);
                    drCurrentRow = dt.NewRow();
                    ViewState["CurrentTable"] = dt;
                    PurchaseMgmtGridView.DataSource = dt;
                    PurchaseMgmtGridView.DataBind();

                    // Delete this
                    //for (int i = 0; i < PurchaseMgmtGridView.Rows.Count - 1; i++)
                    //{
                    //    PurchaseMgmtGridView.Rows[i].Cells[0].Text = Convert.ToString(i + 1);
                    //}
                    SetPreviousData();
                }
            }
        }

I think you trying to access on an object reference that points to null.

Try like this

 private void SetPreviousData()
    {
        if (ViewState["CurrentTable"] != null)
        {
            DataTable dt = (DataTable)ViewState["CurrentTable"];
            if (dt.Rows.Count > 0)
            {
                for (int i = 0; i < dt.Rows.Count-1; i++)
                {
                    DropDownList itemDropDownList =
                      (DropDownList)PurchaseMgmtGridView.Rows[i].Cells[0].FindControl("ItemDropDownList");
                    DropDownList itemUnitDropDownList =
                      (DropDownList)PurchaseMgmtGridView.Rows[i].Cells[1].FindControl("ItemUnitDropDownList");
                    TextBox rateTextBox =
                      (TextBox)PurchaseMgmtGridView.Rows[i].Cells[2].FindControl("RateTextBox");
                    TextBox qtyTextBox =
                      (TextBox)PurchaseMgmtGridView.Rows[i].Cells[3].FindControl("QtyTextBox");
                    Label totalLabel =
                      (Label)PurchaseMgmtGridView.Rows[i].Cells[4].FindControl("TotalLabel");

                    FillItemDropDownList(itemDropDownList);
                    FillItemUnitDropDownList(itemUnitDropDownList);


                    if (i < dt.Rows.Count - 1)
                    {
                        //itemDropDownList.SelectedValue = dt.Rows[i]["Item"].ToString();
                        //itemUnitDropDownList.SelectedValue = dt.Rows[i]["ItemUnit"].ToString();
                        itemDropDownList.ClearSelection();
                        itemDropDownList.Items.FindByText(dt.Rows[i]["Item"].ToString()).Selected = true;
                        itemUnitDropDownList.ClearSelection();
                        itemUnitDropDownList.Items.FindByText(dt.Rows[i]["ItemUnit"].ToString()).Selected = true;
                    }

                    rateTextBox.Text = dt.Rows[i]["Rate"].ToString();
                    qtyTextBox.Text = dt.Rows[i]["Qty"].ToString();
                    totalLabel.Text = dt.Rows[i]["Total"].ToString();                        
                }
            }
        }
    }

Refer here for Null Reference Exception

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM