我正在使用MS Access在ASP.net(C#)中执行一个小应用程序。我有一个Gridview,我有一个“更新”命令。在运行期间,我在RowUpdating()方法中放置了断点。一切正常,没有错误,参数在后面的代码中得到更新。但是在输出中,gridview没有更新,也没有在DB中。
这是代码:
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
string ID = GridView1.Rows[e.RowIndex].Cells[1].Text;
string CName= ((TextBox)GridView1.Rows[e.RowIndex].Cells[2].Controls[0]).Text;
string AName = ((TextBox)GridView1.Rows[e.RowIndex].Cells[3].Controls[0]).Text;
string APhone = ((TextBox)GridView1.Rows[e.RowIndex].Cells[4].Controls[0]).Text;
string AEmail = ((TextBox)GridView1.Rows[e.RowIndex].Cells[5].Controls[0]).Text;
string Note = ((TextBox)GridView1.Rows[e.RowIndex].Cells[6].Controls[0]).Text;
UpdateRecord(ID, CName, AName, APhone, AEmail, Note); // GridView1.EditIndex = -1; BindGridView();
}
UpdateRecord()方法:
更新方法运行良好,在使用断点运行期间,所有参数都获取更新的值,但它不会显示在gridview中,也不会在DB中更新
private void UpdateOrAddNewRecord(string ID, string CName, string AName, string APhone, string AEmail, string Note)
{
OleDbConnection connection = null;
string conStr = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Documents and Settings\arjun.giridhar\Desktop\db1.mdb;Persist Security Info=False";
string sqlStatement = "UPDATE Carriers" + " SET CarrierName = @CarrierName, AccountRepName = @AccountRepName, AccountRepContactPhone = @AccountRepContactPhone, AccountRepEmail= @AccountRepEmail, Notes=@Notes" + " WHERE CarrierID = @CarrierID";
try
{
connection = new OleDbConnection(conStr);
connection.Open();
OleDbCommand cmd = new OleDbCommand(sqlStatement, connection);
cmd.Parameters.AddWithValue("@CarrierID", ID);
cmd.Parameters.AddWithValue("@CarrierName", CName);
cmd.Parameters.AddWithValue("@AccountRepName", AName);
cmd.Parameters.AddWithValue("@AccountRepContactPhone", APhone);
cmd.Parameters.AddWithValue("@AccountRepEmail", AEmail);
cmd.Parameters.AddWithValue("@Notes", Note);
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
string msg = "Update Error:";
msg += ex.Message;
throw new Exception(msg);
}
finally
{
connection.Close();
}
}
BindGridView()方法:
private void BindGridView()
{
DataTable dt = new DataTable();
OleDbConnection connection = new OleDbConnection(conStr);
try
{
connection.Open();
string sqlStatement = "SELECT * FROM Carriers";
OleDbCommand cmd = new OleDbCommand(sqlStatement, connection);
OleDbDataAdapter sqlDa = new OleDbDataAdapter(cmd);
sqlDa.Fill(dt);
if (dt.Rows.Count > 0)
{
GridView1.DataSource = dt;
GridView1.DataSourceID = string.Empty;
GridView1.DataBind();
}
}
catch (System.Data.SqlClient.SqlException ex)
{
string msg = "Fetch Error:";
msg += ex.Message;
throw new Exception(msg);
}
finally
{
connection.Close();
}
}
请给我一个解决方案。
此致 阿琼
答案 0 :(得分:1)
我在这里找到了另一篇文章:Gridview not updating value说这是由于Page_Load
中的网格绑定而没有检查回发引起的。我将Page_load
更改为:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
BindGridView();
}
}
那很有效。