アイテムをグリッドビューに追加するとき、(グリッドビュー エントリから) ファイルを csv 形式に書き込む前に、ユーザーがアイテムを選択して編集/削除できるようにしたいと考えています。「編集」をクリックして情報を更新すると、エラーが発生します。位置 0 に行がありません (または、編集するために選択した行)。これが私のコードです。
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
SetFocus(parttxtbox);
table = new DataTable();
MakeDataTable();
}
else
table = (DataTable)ViewState["table"];
ViewState["table"] = table;
}
protected void MakeDataTable()
{
table.Columns.Add("Part", typeof(string));
table.Columns.Add("Quantity", typeof(Int32));
table.Columns.Add("Ship-To", typeof(string));
table.Columns.Add("Requested Date", typeof(string));
table.Columns.Add("Shipping Method", typeof(string));
//Persist the table in the Session object.
Session["table"] = table;
//Bind data to the GridView control.
BindData();
}
protected void addbtn_Click(object sender, EventArgs e)
{
part = parttxtbox.Text.ToUpper();
shipto = shiptotxtbox.Text;
reqdate = reqdatecal.SelectedDate.ToShortDateString();
shipmthd = shipddl.SelectedItem.ToString();
CreateTable();
}
public void CreateTable()
{
DataRow row = table.NewRow();
row["Part"] = part;
row["Quantity"] = qty;
row["Ship-To"] = shipto;
row["Requested Date"] = reqdate;
row["Shipping Method"] = shipmthd;
table.Rows.Add(row);
griditems.DataSource = table.DefaultView;
griditems.DataBind();
}
private void BindData()
{
griditems.DataSource = table;
griditems.DataBind();
}
protected void griditems_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
//Retrieve the table from the session object.
DataTable dt = (DataTable)Session["table"];
//Update the values.
GridViewRow row = griditems.Rows[e.RowIndex];
dt.Rows[row.DataItemIndex]["Part"] = ((TextBox)(row.Cells[1].Controls[0])).Text;
dt.Rows[row.DataItemIndex]["Quantity"] = ((TextBox)(row.Cells[2].Controls[0])).Text;
dt.Rows[row.DataItemIndex]["Ship-To"] = ((TextBox)(row.Cells[3].Controls[0])).Text;
dt.Rows[row.DataItemIndex]["Requested Date"] = ((TextBox)(row.Cells[4].Controls[0])).Text;
dt.Rows[row.DataItemIndex]["Shipping Method"] = ((DropDownList)(row.Cells[5].Controls[0])).SelectedItem.ToString();
//Reset the edit index.
griditems.EditIndex = -1;
//Bind data to the GridView control.
BindData();
////Somewhat works, doesn't update the part field with the text entered
//TextBox partedit = (TextBox)griditems.Rows[e.RowIndex].FindControl("Part");
//DataRow row = table.NewRow();
//row["Part"] = partedit;
//row["Quantity"] = qty;
//row["Ship-To"] = shipto;
//row["Requested Date"] = reqdate;
//row["Shipping Method"] = shipmthd;
//table.Rows.Add(row);
}
「ある程度動く」とコメントアウトされた部分は、更新をクリックすると更新されるフィールドに空白が書き込まれます。