【问题标题】:I want to ADD the data in the datagridview not create a new one我想在datagridview中添加数据而不是创建一个新的
【发布时间】:2021-05-22 11:08:19
【问题描述】:
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 行是做什么的,但他们在我看到的教程中使用了它们

【问题讨论】:

    标签: c# .net datagridview


    【解决方案1】:

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

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

    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 功能的最佳解决方案,因为每次单击该按钮都会连接 SQL Server 和它的数据库。断开连接也是如此,但出于学习的目的,它很好。最好是在构造函数中连接数据库并在析构函数中断开连接,其中将调用函数 Dispose 和 Close。如果您选择这样做,cmd 对象和 con 对象应在类范围内定义为类的字段(因此在构造函数上方但在类内部的某个位置)。

    【讨论】:

      猜你喜欢
      • 2017-09-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多