我在数据库TextBooks中的表中为绑定数据的Gridview添加了一个编辑/更新选项。我允许这样做,以防管理员可以随后更改信息。目前我可以单击信息中的编辑类型,然后将其绑定到页面上的当前网格,但不将其保存到数据库,并在离开页面并返回到它时,它将恢复为旧值。在将代码跟随BindGrid()方法之后,我相信我在某个地方出了问题,但无法完全掌握它是什么,我错过了。
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
DataTable dt = new DataTable();
string query = "select * from textBooks ";
using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["HUTDMSConnectionString"].ToString()))
using (SqlDataAdapter adapter = new SqlDataAdapter(query, connection))
adapter.Fill(dt);
ViewState["allBooks"] = dt;
this.BindGrid();
}
}
protected void BindGrid()
{
GridView1.DataSource = ViewState["allBooks"] as DataTable;
GridView1.DataBind();
}
protected void OnRowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
this.BindGrid();
}
protected void OnUpdate(object sender, EventArgs e)
{
GridViewRow row = (sender as LinkButton).NamingContainer as GridViewRow;
string Ancillary = (row.Cells[3].Controls[0] as TextBox).Text;
string BookActive = (row.Cells[4].Controls[0] as TextBox).Text;
string InactiveDate = (row.Cells[6].Controls[0] as TextBox).Text;
string Author = (row.Cells[7].Controls[0] as TextBox).Text;
string Publisher = (row.Cells[8].Controls[0] as TextBox).Text;
string EditionAndDate = (row.Cells[9].Controls[0] as TextBox).Text;
string Imprint = (row.Cells[10].Controls[0] as TextBox).Text;
string eISBN = (row.Cells[13].Controls[0] as TextBox).Text;
string ebookAvailable = (row.Cells[14].Controls[0] as TextBox).Text;
string Notes = (row.Cells[15].Controls[0] as TextBox).Text;
DataTable dt = ViewState["allBooks"] as DataTable;
dt.Rows[row.RowIndex]["Ancillary"] = Ancillary;
dt.Rows[row.RowIndex]["BookActive"] = BookActive;
dt.Rows[row.RowIndex]["InactiveDate"] = InactiveDate;
dt.Rows[row.RowIndex]["Author"] = Author;
dt.Rows[row.RowIndex]["Publisher"] = Publisher;
dt.Rows[row.RowIndex]["EditionAndDate"] = EditionAndDate;
dt.Rows[row.RowIndex]["Imprint"] = Imprint;
dt.Rows[row.RowIndex]["eISBN"] = eISBN;
dt.Rows[row.RowIndex]["ebookAvailable"] = ebookAvailable;
dt.Rows[row.RowIndex]["Notes"] = Notes;
ViewState["allBooks"] = dt;
GridView1.EditIndex = -1;
this.BindGrid();
}
答案 0 :(得分:0)
所以你目前正在做的是从数据库中提取数据,将其存储在gridview中,然后在GridView中编辑数据。一旦调用该databind命令,该数据就会独立于数据库。为了将这些数据保存到数据库,我建议在OnUpdate方法中使用SqlDataAdapter的Update method。这将允许您将更新值存储回数据行并将其保存到数据库,同时遵循与填充GridView时类似的策略。