从网格中删除行无效

时间:2012-11-30 06:13:25

标签: c# asp.net gridview

我正在使用Viewstate Concept向网格添加新行。但我无法删除最后一行。默认情况下,我将空行绑定到网格。

//添加新行

if (ViewState["CurrentTable"] != null)
        {
            DataTable dtCurrentTable = (DataTable)ViewState["CurrentTable"];
            DataRow drCurrentRow = null;
            int i;

            if (dtCurrentTable.Rows.Count > 0)
            {
                for (i = 1; i <= dtCurrentTable.Rows.Count; i++)
                {
                    TextBox txtguide = (TextBox)grdreports.Rows[rowIndex].FindControl("txtAccNo");
 dtCurrentTable.Rows[i - 1]["txtAccNo"] = txtguide.Text;
  }
                drCurrentRow = dtCurrentTable.NewRow();
                dtCurrentTable.Rows.Add(drCurrentRow);
                ViewState["CurrentTable"] = dtCurrentTable;
                ViewState["rowcount"] = dtCurrentTable.Rows.Count;
                grdreports.DataSource = dtCurrentTable;
                grdreports.DataBind();

            }

//删除最后一行

if (Grid.Rows.Count > 1)
    {
        if (ViewState["CurrentTable"] != null)
        {
            DataTable dtCurrentTable = (DataTable)ViewState["CurrentTable"];
            dtCurrentTable.Rows.RemoveAt(dtCurrentTable.Rows.Count);
            ViewState["CurrentTable"] = dtCurrentTable;
            Grid.DataSource = dtCurrentTable;
            Grid.DataBind();

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

我哪里错了?

2 个答案:

答案 0 :(得分:0)

删除时取计数并从中减去1。它会工作。

if (Grid.Rows.Count > 1)
        {
            if (ViewState["CurrentTable"] != null)
            {
                DataTable dtCurrentTable = (DataTable)ViewState["CurrentTable"];
                dtCurrentTable.Rows.RemoveAt(dtCurrentTable.Rows.Count -1);
                ViewState["CurrentTable"] = dtCurrentTable;
                Grid.DataSource = dtCurrentTable;
                Grid.DataBind();

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

答案 1 :(得分:0)

DataTable.Rows是一个基于0的索引。如果要删除最后一行,则应使用count - 1

dtCurrentTable.Rows.RemoveAt(dtCurrentTable.Rows.Count - 1);