グリッドビューから行を削除しようとしていますが、そうすると、他の行の他のコントロールから現在の値が削除されます。
ランダムな行を削除した後、次のエラーも発生します。
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");
}
}
}
ご協力いただきありがとうございます