在datagridview中保留行

时间:2016-04-02 07:29:48

标签: c# visual-studio-2010 datagridview

我希望在选定的组合框值上将行从数据库移动到datagridview

private void test_Load(object sender, EventArgs e)
{

    string    str = "select * from sale_tab";
    cmd = new SqlCommand(str, con);
    SqlDataReader reader = cmd.ExecuteReader();
    while (reader.Read())
    {
        comboBox1.Items.Add(reader["Item_name"].ToString());
    }
    reader.Close();
    con.Close();
} 

它显示行但是当我在组合框中单击下一个值时它显示新行但是第一行不会保留在gridview中我希望它保持所有行例如我从组合框中单击书它显示显示书详细信息和何时我点击计算机它应该在书籍细节下添加行

private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{ 

   str = "select * from sale_tab where item_name='" + comboBox1.Text + "'";
   cmd = new SqlCommand(str, con);
   sda = new SqlDataAdapter(cmd);
   DataSet ds = new DataSet();
   sda.Fill(ds, "sale_tab");
   dataGridView1.DataMember = "sale_tab";
   dataGridView1.DataSource = ds;
   con.Close()
}

1 个答案:

答案 0 :(得分:0)

您的dataGrid交换所有选项的原因是因为这些行   DataSet ds = new DataSet(); sda.Fill(ds, "sale_tab"); dataGridView1.DataMember = "sale_tab"; dataGridView1.DataSource = ds; 如果你创建了一个gobal datatable变量,那么你可以在方法中使用temp数据表,这样你就可以像这样将数据表组合在一起

Golbal variable:
datatable dtAll = new datatable();

//put this inside the method body
datatable _dt = new datatable(); 
  str = "select * from sale_tab where item_name='" + comboBox1.Text + "'";
   cmd = new SqlCommand(str, con);
   using (SqlDataAdapter _da = new SqlDataAdapter(_cmd))
    {
        _da.Fill(_dt);
    }
   dtAll.Merge(_dt);

   dataGridView1.DataSource = dtAll;
   con.Close()

希望这会有所帮助