繁体   English   中英

我想在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();
    }

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

最后四行表示将来自名为da的 SqlDataAdapter object 的数据填充到新创建的名为dt的空数据表 object 中。 之后设置这个填充的 object 调用dtdataGridView2作为它使用 DataGridView.DataSource 属性的数据源。 After that it is calling upon object cmd function Dispose which releases any resources that object is using for eg memory consumed by this object. 最后关闭与 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();
    }

请注意,这不是您应该如何关闭连接或使用 dispose function 的最佳解决方案,因为每次单击该按钮都会连接 SQL 服务器及其数据库。断开连接相同,但为了学习它很好。 最好是在构造函数中连接数据库并在析构函数中断开连接,其中将调用函数 Dispose 和 Close。 If you choose to do it in this way cmd object and con object should be defined at class scope as fields of class (so somewhere above constructor but inside of class).

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM