更新时间:2023-12-01 10:44:28
假设其他一切都在您这边工作正常,主要问题是您使用的 Update
命令包含在您的cmd
变量,您之前用于更新数据库,尝试用更新的值填充您的 dt
.相反,您必须为此使用 Select
命令,如下所示:
Assuming everything else is working fine on your side, the main problem is that you're using the same Update
command contained in your cmd
variable, that you used before to update the database, to try to fill your dt
with the updated values. Instead you must use a Select
command for that purpose, as follows:
改变这个:
DataTable dt = new DataTable();
SqlDataAdapter adap = new SqlDataAdapter(cmd);
adap.Fill(dt);
//dataGridViewAFp1.DataSource = dt;
为此:
DataTable dt = new DataTable();
SqlDataAdapter adap = new SqlDataAdapter("select * from P1", conn);
adap.Fill(dt);
dataGridViewAFp1.DataSource = dt;
添加完整的工作代码.在此示例中,从 100.00
到 200.00
(watch) 的前 2 个数据行更新 ListPrice
列(列索引 9).我正在使用您的代码,只是更改了表名和列名.
Adding full working code. In this sample, column ListPrice
(column index 9) is updated for the first 2 data rows from 100.00
to 200.00
(watch). I'm using your code, just changing table and column names.
private void btnEnterAFp1_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(@"Data Source=(LocalDB)MSSQLLocalDB;AttachDbFilename=|DataDirectory|AdventureWorks2014.mdf;Integrated Security=True;Connect Timeout=30");
decimal AF2;
decimal AF11;
decimal ResultAF;
if (string.IsNullOrWhiteSpace(txtp1AF.Text))
{
MessageBox.Show("Please Enter fee", "Oops", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
else
{
if (dataGridViewAFp1.Rows[0].Cells[9].Value != null)
{
conn.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
decimal.TryParse(dataGridViewAFp1.Rows[0].Cells[9].Value.ToString(), out AF11);
AF2 = Convert.ToDecimal(txtp1AF.Text);
ResultAF = AF11 + AF2;
String updatedAF = Convert.ToString(ResultAF);
cmd.CommandText = @"Update Production.Product set ListPrice=@af where Name = 'Adjustable Race' OR Name = 'Bearing Ball'";
cmd.Parameters.AddWithValue("@af", updatedAF);
int n = cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
SqlDataAdapter adap = new SqlDataAdapter("select * from Production.Product", conn);
adap.Fill(dt);
dataGridViewAFp1.DataSource = dt;
conn.Close();
MessageBox.Show("Record Updated Successfully ");
txtp1AF.Text = " ";
}
}
}