簡體   English   中英

如何刪除動態Gridview中的行?

[英]How to delete a row in dynamic Gridview?

我作為一個測試項目,在ASP.NET中使用一個簡單的庫存系統。 在一個頁面中,我必須創建用於輸入購買詳細信息的頁面! 我使用動態gridview來簡化數據輸入。 我已經使用了本教程本文,但我在刪除gridview中的行時遇到了問題。 我看過這個類似的帖子,但沒有幫助。

aspx代碼如下 -

<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>

這是aspx.cs代碼 -

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");
        }
     }
   }
}

這些代碼會產生這樣的結果

在此輸入圖像描述

但是,一旦我開始刪除其中一行,它就會給我這個例外 -

在此輸入圖像描述

從以下代碼中的SetPreviousData()方法拋出此異常 -

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

知道我哪里錯了嗎?

PS:代碼更新I [提供實體列表的代碼ieItem和ItemUnit]

看起來它實際上不是刪除GridView中的行而是問題,而是其他東西。

首先,需要注意兩件事 - 我無法編譯,因為我沒有ItemItemUnit的定義,所以我通過閱讀代碼來做到這一點。 其次,我還沒喝完咖啡! (更新:我的咖啡已經完成!)

看起來SetPreviousData()itemDropDownList的引用為null,因此請查看原因。 使用foreach循環來迭代遍歷DataTable的行可能更容易,以避免基於0的索引和count-1比較等的任何問題。(更新:它仍然會更容易,但它不會導致問題。 )

另外,不確定是否要這樣做,但是獲取ItemDropDownList的FindControl語句使用的rowIndex總是等於i (更新:再次,可以幫助只是清理代碼,但這不是一個要求。)

首先弄清楚當它崩潰時i是什么,看看你的預期是什么,並找出FindControl語句無法正常工作的原因。 如果它為0,則可能是嘗試讀取標題行或不存在該Dropdown的內容。

對不起,我不能給你一個明確的解決方案,但希望這會有所幫助。

解決方案:獲得完整代碼后,更容易看到發生了什么。 基本上, PurchaseMgmtGridView_RowDeleting方法是從GridView中刪除DropdownList,然后SetPreviousData()試圖讀取不存在的東西。 SetPreviousDataFindControl語句返回NULL,如錯誤消息中所示,但不是我之前推測的原因。

PurchaseMgmtGridView_RowDeleting方法中刪除違規行,您將全部設置完畢。

  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();
                }
            }
        }

我認為您嘗試訪問指向null的對象引用。

試試這樣吧

 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();                        
                }
            }
        }
    }

請參閱此處的空引用異常

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM