我想在 datagridview 中添加数据而不是创建新数据

I want to ADD the data in the datagridview not create a new one

private void button5_Click(object sender, EventArgs e)
    {
        textBox4.Text = textBox3.Text;
        SqlConnection con = new SqlConnection(sqlstring);
        con.Open();

        string sql = "SELECT productid, name, ListPrice as Price FROM Production.Product where 
                      ProductID = @productid";

        SqlCommand cmd = new SqlCommand(sql, con);
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        cmd.Parameters.Add("@productid", SqlDbType.Int).Value = int.Parse(textBox4.Text);
        DataTable dt = new DataTable();

        da.Fill(dt);
        dataGridView2.DataSource = dt;
        cmd.Dispose();
        con.Close();
    }

我想添加新行而不是删除前一行然后添加新行 sql string 是在开始时初始化的 const 我不知道最后 4 行是做什么的,但他们在我看到的教程中使用了它们

最后四行表示将名为 da 的 SqlDataAdapter 对象中的数据填充到名为 dt 的新创建的空 DataTable 对象中。之后,将这个名为 dt 的填充对象设置为 dataGridView2,因为它是使用 DataGridView.DataSource 属性 的数据源。之后它调用对象 cmd 函数 Dispose 释放该对象正在使用的任何资源,例如该对象消耗的内存。最后,您关闭了与 sql 服务器的连接。

尝试像这样修改您的代码:

private void button5_Click(object sender, EventArgs e)
    {
        textBox4.Text = textBox3.Text;
        SqlConnection con = new SqlConnection(sqlstring);
        con.Open();

        string sql = "SELECT productid, name, ListPrice as Price FROM Production.Product where 
                      ProductID = @productid";

        SqlCommand cmd = new SqlCommand(sql, con);
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        cmd.Parameters.Add("@productid", SqlDbType.Int).Value = int.Parse(textBox4.Text);
        DataTable dt = new DataTable();
        
        DataTable dtOrig = ((DataTable)dataGridView2.DataSource);
         
        if(dtOrig != null)
        {
            da.Fill(dt);
            
            foreach(DataRow row in dt.Rows)
            {
                  dtOrig.Rows.Add(row);
            }
        }
        else
        {
             da.Fill(dt);
             dataGridView2.DataSource = dt;
        }

        cmd.Dispose();
        con.Close();
    }

请注意,这不是关闭连接或使用处置功能的最佳解决方案,因为每次单击该按钮都会连接 SQL 服务器及其数据库。断开连接也是如此,但为了学习目的,这很好.最好是在构造函数中连接数据库并在将调用函数 Dispose 和 Close 的析构函数中断开连接。如果您选择以这种方式执行此操作,cmd 对象和 con 对象应在 class 范围内定义为 [=32] 的字段=](所以在构造函数之上但在 class 内部的某处)。