如何为列添加值并更新数据库
我试图将dataGridViewAFp1
中的Annual_Fees列的值添加到我转换为整数的文本框txtp1AF.Text
中的新值AF2 。 然后,添加ResultAF的结果将转换回字符串updatedAF ,这是要在数据库中更新的值。 我将变量AF11初始化为0.查询确实更新了所选列。 想法是获得AF2中的任何值,并将其添加到该列和行中的任何值,具体是我在数据库中放入AF11 ,因此更新值updatedAF 。 这是我到目前为止所做的,但似乎没有起作用。 这些值没有加起来。
private void btnEnterAFp1_Click(object sender, EventArgs e) { if (string.IsNullOrWhiteSpace(txtp1AF.Text)) { MessageBox.Show("Please Enter fee","Oops",MessageBoxButtons.OK,MessageBoxIcon.Warning); } else { if (dataGridViewAFp1.Rows[0].Cells["Annual_Fees"].Value != null) { conn.Open(); SqlCommand cmd = new SqlCommand(); cmd.Connection = conn; int.TryParse(dataGridViewAFp1.Rows[0].Cells["Annual_Fees"].Value.ToString(), out AF11); AF2 = Convert.ToInt32(txtp1AF.Text); ResultAF = AF11 + AF2; String updatedAF = Convert.ToString(ResultAF); cmd.CommandText = @"Update P1 set Annual_Fees=@af where Sponsorship_Status = 'Sponsored' OR Sponsorship_Status = 'Unsponsored' OR Sponsorship_Status = 'Formerly Sponsored' "; cmd.Parameters.AddWithValue("@af", updatedAF); cmd.ExecuteNonQuery(); DataTable dt = new DataTable(); SqlDataAdapter adap = new SqlDataAdapter(cmd); adap.Fill(dt); //dataGridViewAFp1.DataSource = dt; conn.Close(); MessageBox.Show("Record Updated Successfully "); txtp1AF.Text = " "; }
假设其他一切工作正常,主要问题是您使用的cmd
变量中包含的相同Update
命令,您之前用来更新数据库,尝试使用更新的值填充您的dt
。 相反,您必须为此目的使用Select
命令,如下所示:
改变这个:
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;
编辑:添加完整的工作代码。 在此示例中, ListPrice
100.00
到200.00
(监视)的前2个数据行更新列ListPrice
(列索引9)。 我正在使用您的代码,只是更改表名和列名。
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 = " "; } } }