将项目添加到 gridview 时,我希望用户能够在将文件(从 gridview 条目)写入 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);
}
当您单击更新时,注释掉的“有些工作”部分将在更新的字段中写入空白。