我从msdn复制了大部分内容。点击更新不会做任何事情
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
try
{
DataTable dt = (DataTable)Session["hospital"];
GridViewRow row = GridView1.Rows[e.RowIndex];//getting current index
dt.Rows[row.DataItemIndex]["NAME"] = ((TextBox)(row.Cells[0].Controls[0])).Text;
dt.Rows[row.DataItemIndex]["phone_no."] = ((TextBox)(row.Cells[1].Controls[0])).Text;
dt.Rows[row.DataItemIndex]["ADDRESS"] = ((TextBox)(row.Cells[2].Controls[0])).Text;
dt.Rows[row.DataItemIndex]["HOS_ID"] = ((TextBox)(row.Cells[3].Controls[0])).Text;
GridView1.EditIndex = -1;
gvbind(GridView1, "select * from HOSPITAL"); //
}
catch(OracleException ex)
{
lblresult.Text = ex.Message.ToString();
}
catch (NullReferenceException nx)
{
lblresult.Text = nx.Message.ToString();
}
}
Jere是将gridview
绑定到datasource
的函数。
public void gvbind(GridView g, string sql)
{
try
{
conn.Open();
OracleCommand cmd = new OracleCommand();
cmd.Connection = conn;
cmd.CommandText = sql;
cmd.CommandType = CommandType.Text;
// cmd.ExecuteNonQuery();
OracleDataAdapter da = new OracleDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
Session["hospital"] = ds.Tables[0];
if (ds.Tables[0].Rows.Count > 0)
{
g.DataSource = ds;
g.DataBind();
}
else
{
ds.Tables[0].Rows.Add(ds.Tables[0].NewRow());
g.DataSource = ds;
g.DataBind();
int columncount = g.Rows[0].Cells.Count;
g.Rows[0].Cells.Clear();
g.Rows[0].Cells.Add(new TableCell());
g.Rows[0].Cells[0].ColumnSpan = columncount;
g.Rows[0].Cells[0].Text = "No Records Found";
}
conn.Close();
conn.Dispose();
}
}
这是 asp.net 代码<我是否需要添加编辑模板和itemtemplate才能使用此>
<asp:GridView ID="GridView1" runat="server" DataKeyNames="HOS_ID" AutoGenerateColumns="False" OnRowDeleting="GridView1_RowDeleting" OnPageIndexChanging="GridView1_PageIndexChanging"
OnRowUpdating="GridView1_RowUpdating" OnRowEditing="GridView1_RowEditing"
OnRowCancelingEdit="GridView1_RowCancelingEdit">
<Columns>
<asp:BoundField DataField="NAME" HeaderText="name" />
<asp:BoundField DataField="phone_no." HeaderText="Phone_no." />
<asp:BoundField DataField="ADDRESS" HeaderText="address" />
<asp:BoundField DataField="HOS_ID" HeaderText="hos_id"/>
<asp:CommandField ShowEditButton="true" />
<asp:CommandField ShowDeleteButton="true" />
</Columns>
</asp:GridView>
答案 0 :(得分:0)
问题似乎是代码使用DataTable
中已编辑行的值填充GridView1_RowUpdating
,但在调用gvbind
时丢弃它们。存储在DataTable
中的Session["hospital"]
是上次更新网格时从数据库加载的数据的副本。更改值只会更改内存中的副本,而不是基础表。
相反,GridView1_RowUpdating
应该:
DataTable
填充DataAdapter
。DataTable
中找到与网格中更新的行对应的行。DataTable
。DataTable
更新网格。这包括此页面之外的其他人所做的更改。