1

我制作了一个 C# prog,其中有一个按钮(名为 insert)和一个 datagridview。我已经输入了一个 cmd,如果我在 dvg 新行中输入一个新值,那么在单击插入按钮后会显示一个 msg 框,描述我输入的值。现在我想要一个名为 update..so dat 的第二个按钮,当我单击时在插入新值后,新值会在我的 sql 数据库中更新。

这是我的代码片段-

private void button1_Click_1(object sender, EventArgs e)
 {
 //InsertInfo();


 foreach (int rowIndex in lstNewRows)
 {

 MessageBox.Show(dataGridView1.Rows[rowIndex].Cells[0].Value + "; " +
 dataGridView1.Rows[rowIndex].Cells[1].Value);
 }

 lstNewRows.Clear();
 }

 private void dataGridView1_DefaultValuesNeeded_1(object sender, DataGridViewRowEventArgs e)
 {

 lstNewRows.Add(e.Row.Index);

 }
private void updateInfo()
 {

 String strConnection = "Data Source=HP\\SQLEXPRESS;database=MK;Integrated Security=true";


 SqlConnection con = new SqlConnection(strConnection);
 using (SqlConnection sqlConn = new SqlConnection(strConnection))
 {
 using (SqlCommand cmd = new SqlCommand())
 {
 int rowIndex;
 cmd.CommandText = @"UPDATE tble SET " +
 "name = @name, " +
 "number = @number" = (int)dataGridView1.SelectedCells[0].Value + " ";

 cmd.Parameters.Add("@name", SqlDbType.VarChar, 50, "name");
 cmd.Parameters.Add("@number", SqlDbType.VarChar, 50, "number");



 cmd.Connection = sqlConn;



 using (SqlDataAdapter da = new SqlDataAdapter())
 {
 DataTable dtRecord = new DataTable();
 da.UpdateCommand = cmd;
 da.Update(dtRecord);

 }
 }

 }
 }

 private void button2_Click(object sender, EventArgs e)
 {
 updateInfo();
 }
 }

}

4

1 回答 1

0

我假设您在更新行值时遇到问题。您updateInfo();在很多地方都错了,这是正确的版本:

String strConnection = "Data Source=HP\\SQLEXPRESS;database=MK;Integrated Security=true";
//SqlConnection con = new SqlConnection(strConnection); not needed
using (SqlConnection sqlConn = new SqlConnection(strConnection))
{
      using (SqlCommand cmd = new SqlCommand())
      {
            int rowIndex = 1; //row index to update?
            var number = Int32.Parse(dataGridView1.Rows[rowIndex].Cells[0].Value.ToString());  //assuming Cells[0] holds number
            var name = dataGridView1.Rows[rowIndex].Cells[1].Value.ToString();                 //as above
            var id = Int32.Parse(dataGridView1.Rows[rowIndex].Cells[3].Value.ToString());      //get id
            //your old command text was completly wrong
            cmd.CommandText = @"UPDATE tble SET  name = @name, number = @number where id =  @id"; //id and @id is key for row to update
            cmd.Parameters.Add("@name", name);
            cmd.Parameters.Add("@number", number);
            cmd.Parameters.Add("@id", id);

            cmd.Connection = sqlConn;
            sqlConn.Open();

            cmd.ExecuteNonQuery();
      }

}

我将您的命令字符串更改为有效的命令字符串。同样在您的原始代码中,您没有检索要更新的行 id,因此我为此添加了标记,您应该将其更改为正确的一个(变量id)。

希望这可以帮助 :)

于 2013-02-20T09:03:56.447 回答