protected void UpdateCustomer(object sender, GridViewUpdateEventArgs e)
{
string CustomerID = ((Label)GridView1.Rows[e.RowIndex]
.FindControl("lblCustomerID")).Text;
string Name = ((TextBox)GridView1.Rows[e.RowIndex]
.FindControl("txtContactName")).Text;
string Company = ((TextBox)GridView1.Rows[e.RowIndex]
.FindControl("txtCompany")).Text;
MySqlConnection con = new MySqlConnection();
string Connection = "Server=localhost;" +
"DATABASE=northwind2007;" + "username=;" +
"PASSWORD=;";
con.ConnectionString = Connection;
MySqlCommand cmd = new MySqlCommand();
cmd = new MySqlCommand(cmd.CommandText, con);
cmd.CommandType = CommandType.Text;
cmd.CommandText = "update Customers set FirstName=@ContactName," +
"Company=@CompanyName where ID=@CustomerID;" + "select ID,FirstName,Company from Customers";
cmd.Parameters.AddWithValue("@CustomerID", MySqlDbType.VarChar).Value = CustomerID;
cmd.Parameters.AddWithValue("@ContactName", MySqlDbType.VarChar).Value = Name;
cmd.Parameters.AddWithValue("@CompanyName", MySqlDbType.VarChar).Value = Company;
GridView1.EditIndex = -1;
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
}
我已经尝试了一切,但它现在正在运行,每次我尝试从我的网格更新记录时都会抛出此错误。
答案 0 :(得分:3)
请勿使用AddWithValue
,Add
:
cmd.Parameters.Add("@CustomerID", MySqlDbType.VarChar).Value = CustomerID;
否则MySqlDbType.VarChar
被视为值。
您还应该执行update-command,并且需要Open
连接:
con.Open();
int updatedRecords = cmd.ExecuteNonQuery();
如果您想在之后填写表格,可以使用DataAdapter
:
using(var da = new MySqlDataAdapter("select ID,FirstName,Company from Customers", con))
da.Fill(dt);
请注意,您应始终使用using
- 语句来确保将处置任何非托管资源并关闭连接(即使出现错误)。例如:
using(var con = new MySqlConnection())
using(var cmd = new MySqlCommand("UPDATE ...", con))
{
con.Open();
cmd.ExecuteNonQuery();
}