【问题标题】:keeping rows in datagridview在datagridview中保留行
【发布时间】:2016-04-02 07:29:47
【问题描述】:

我想在选定的组合框值上将行从数据库移动到 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()
}

【问题讨论】:

    标签: c# visual-studio-2010 datagridview


    【解决方案1】:

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

    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()
    

    希望对你有帮助

    【讨论】:

    • @pål-jørgenvaldersnesas 我是 .net 的新手,请您进一步解释一下。
    • 阅读这篇文章你应该可以理解stackoverflow.com/questions/12900062/…唯一的区别是你需要制作本地临时数据表以便你将它们与dtAll.Merge(dtTemp);合并;
    • 这篇文章介绍了如何在组合框中添加数据,但我的问题不是在组合框中添加数据,而是在选择组合框值时,它会在网格视图中按行显示数据,就像我选择第一个项目一样show 显示所有细节,当我点击第二个时,它应该显示所有细节,谢谢
    • 我已经编辑了答案以提供您需要修复的确切内容,但本网站的重点主要是指导您找到所需的答案,而不是不必要地给您代码
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-07-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-14
    • 1970-01-01
    相关资源
    最近更新 更多