gridview删除行

时间:2012-05-25 11:23:35

标签: c# asp.net gridview

我正在尝试从gridview中删除行 - 但是当我这样做时,会删除其他行中其他控件的当前值。

删除随机行后,我也会收到以下错误。

Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index

protected void gvShoppingCart_RowCommand(object sender, GridViewCommandEventArgs e)
{
    //This is the method that responds to the Remove button's click event
    #region remove item

    if (e.CommandName == "Remove")
    {
        int rowid = Convert.ToInt32(e.CommandArgument);
        //Response.Write(rowid);
        // Response.End();
        //Gridview1.DeleteRow(rowid);
        //Response.Write(Convert.ToInt32(e.CommandArgument));
        // Response.End();
        int rowIndex = rowid;
        if (ViewState["CurrentTable"] != null)
        { 
            DataTable dtCurrentTable = (DataTable)ViewState["CurrentTable"];

            DataRow drCurrentRow = null;

            if (dtCurrentTable.Rows.Count > 0)
            {
                for (int i = 0; i < dtCurrentTable.Rows.Count; i++)
                {
                    TextBox box1 = (TextBox)Gridview1.Rows[rowIndex - 1].Cells[1].FindControl("TextBox1");

                    TextBox box2 = (TextBox)Gridview1.Rows[rowIndex - 1].Cells[2].FindControl("TextBox2");

                    TextBox box3 = (TextBox)Gridview1.Rows[rowIndex - 1].Cells[3].FindControl("TextBox3");

                    TextBox box4 = (TextBox)Gridview1.Rows[rowIndex - 1].Cells[4].FindControl("TextBox4");
                    TextBox box5 = (TextBox)Gridview1.Rows[rowIndex - 1].Cells[5].FindControl("TextBox5");
                    box1.Text = dtCurrentTable.Rows[i]["Column1"].ToString();

                    box2.Text = dtCurrentTable.Rows[i]["Column2"].ToString();

                    box3.Text = dtCurrentTable.Rows[i]["Column3"].ToString();

                    box4.Text = dtCurrentTable.Rows[i]["Column4"].ToString();
                    box5.Text = dtCurrentTable.Rows[i]["Column5"].ToString();
                }

                dtCurrentTable.Rows.RemoveAt(rowid - 1);

                /*dtCurrentTable.Rows[i - 1]["Column1"] = box1.Text;

                dtCurrentTable.Rows[i - 1]["Column2"] = box2.Text;

                dtCurrentTable.Rows[i - 1]["Column3"] = box3.Text;
                dtCurrentTable.Rows[i - 1]["Column4"] = box4.Text;
                dtCurrentTable.Rows[i - 1]["Column5"] = box5.Text;*/
            }

            ViewState["CurrentTable"] = dtCurrentTable;

            Gridview1.DataSource = dtCurrentTable;

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

感谢您的帮助

1 个答案:

答案 0 :(得分:0)

将你的病情改为......

if (dtCurrentTable.Rows.Count > 0 && dtCurrentTable.Rows.Count > rowIndex)

注意: 你确定e.CommandArgument给出了那个特定行的索引吗?