我试图更新我的datagridview。(已编辑)
我的代码:
private void button1_Click(object sender, EventArgs e)
{
con = new System.Data.SqlClient.SqlConnection();
con.ConnectionString = "Data Source=tcp:SHEN-PC,49172\\SQLEXPRESS;Initial Catalog=LSEStock;Integrated Security=True";
con.Open();
if (dataGridView1.Rows.Count > 0)
{
int nRowIndex = dataGridView1.Rows.Count-2;
if (dataGridView1.Rows[nRowIndex].Cells[1].Value != null)
{
textBox2.Text = Convert.ToString(dataGridView1.Rows[nRowIndex].Cells[1].Value);
String updateData = "UPDATE CostPrice SET SupplierName = @SupplierName, CostPrice = @CostPrice WHERE PartsID = '" +textBox1.Text+"'";
SqlCommand update = new SqlCommand(updateData, con);
SqlDataAdapter adapter = new SqlDataAdapter(updateData, con);
update.Parameters.Add("@SupplierName", SqlDbType.NVarChar, 50, "SupplierName");
update.Parameters.Add("@CostPrice", SqlDbType.NVarChar, 50, "CostPrice");
adapter.UpdateCommand = update;
//update.ExecuteNonQuery();
if (update != null)
{
update.Dispose();
update = null;
}
}
else
{
MessageBox.Show("NULL");
}
}
con.Close();
}
它说 ExecuteNonQuery 未初始化。我的代码有什么问题?
我是用SqlCommand来更新的,但是我从网上看到的几乎每个人都在用SqlDataAdapter,有什么区别呢?提前致谢。
如果您有更好的代码,我想从中学习。谢谢!