我正在开发一个 ASP.Net C# Web 应用程序,它包含一个 GridView 来显示我的数据库中某个表的记录,我使用 ODBC Connection 连接到它,并使用 DataSet 在其中保存数据并对其进行编辑,然后我应该保存数据使用在 DataSet 中所做的更改到数据库。
我可以使用 OdbcDataAdapter 的 fill() 方法成功访问数据库,并且可以进行数据绑定,以便在 GridView 中查看数据。
我的问题是,当任何更新或更改完成时,如何将 gridview 保存到数据集然后保存到数据库中[之前完成的操作反之亦然]?
我在 Web 表单类中使用的示例代码如下:-
private void SelectFromDatabase()
{
string OdbcConnectionString1 = getConnectionString();
OdbcConnection OdbcConnection1 = new OdbcConnection(OdbcConnectionString1);
string OdbcSelectText1 = "SELECT * FROM table";
OdbcCommand OdbcSelectCommand1 = new OdbcCommand(OdbcSelectText1, OdbcConnection1);
OdbcDataAdapter OdbcDataAdapter1 = new OdbcDataAdapter();
try
{
OdbcConnection1.Open();
OdbcDataAdapter1.SelectCommand = OdbcSelectCommand1;
OdbcDataAdapter1.AcceptChangesDuringFill = true;
int FillResult = OdbcDataAdapter1.Fill(myDataSet, TableName);
myDataSet.AcceptChanges();
fillGridViewbyDataset(myGridView, myDataSet, TableName);
Response.Write("<br/>SelectFromDatabase() Fill Result: " + FillResult);
}
catch (Exception Exception1)
{
Response.Write("<br/> SelectFromDatabase() Exception: " + Exception1.Message);
}
finally
{
OdbcConnection1.Close();
}
}
private void fillGridViewbyDataset(GridView gv, DataSet ds, string dt)
{
gv.DataSource = ds;
gv.DataMember = dt;
gv.DataBind();
}
what I need is something like:-
how to save Gridview to the DataSet then save the DataSet to the database as i got the gridview updates but the database still without any updates !!
如果我有一个名为 myDs 的数据集,并且我通过在循环中直接访问来编辑其中的一个字段,如下所示:-
for (int i = 0; i < myDS.Tables[TableName].Rows.Count; i++)
{
//some function or web method to get the id value of the record being updated
int n = getNewNumber();
//updating the dataset record according to some condition
if (n == 0)
{
myDS.Tables[TableName].Rows[i]["id"] = n;
myDS.Tables[TableName].Rows[i]["description"] = "some data";
}
else
{
myDS.Tables[TableName].Rows[i]["id"] = n;
myDS.Tables[TableName].Rows[i]["description"] = "new data";
}
}
我如何在数据库中完成这些更改,因为我可以在执行 databind() 时在 GridView 中看到它,但数据库不受影响,我尝试使用 OdbcDataAdapter 和 OdbcCommandBuilder 的填充和更新方法?
请这是紧急的,因为我需要它来开发一个重要的应用程序..
提前感谢您的回复和回答......