【问题标题】:How to show record in DataGridView based on selected ComboBox item?如何根据选定的 ComboBox 项在 DataGridView 中显示记录?
【发布时间】:2018-07-09 16:54:52
【问题描述】:

我正在制作 Windows 应用程序并且卡在一个地方。 我的问题是我想通过选择ComboBox 项目在DataGridView 中显示记录,但我不明白正确的方法。请帮我解决这个问题。

private void grid_Load(object sender, EventArgs e)
{
con = new SqlConnection(constr);

    try
    {
        con.Open();
        //this.studTableAdapter.Fill(this.pRJTestDBDataSet.stud);
        //above line show error for connection to database

        da = new SqlDataAdapter("SELECT stud_no FROM stud", con);
        DataTable dt = new DataTable();
        da.Fill(dt);
        comboBox1.DataSource = dt;
        comboBox1.DisplayMember = "stud_no";
        comboBox1.ValueMember = "stud_no";
        comboBox1.DataSource = dt;
        comboBox1.SelectedIndex = -1;
        comboBox1_SelectedIndexChanged(sender, e);
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
    finally
    { con.Close(); }
}

private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
    this.studTableAdapter.Fill(pRJTestDBDataSet.stud);
    //above line show error for connection to database
}

我已经尝试了上面的代码,但是它在那里不起作用,比如登录失败用户

【问题讨论】:

  • 你应该分享一些你已经尝试过的代码。

标签: c# datagridview combobox


【解决方案1】:
    cmd = new SqlCommand("SELECT stud_no FROM stud", con);
    da = new SqlDataAdapter(cmd);

    da.Fill(dt);
    Combobox1.DataSource = dt;
    Combobox1.DisplayMember = dt.Columns("Stud_no").ToString;

【讨论】:

    【解决方案2】:

    在 Combo Box 的每个 SelectedItemIndex 更改事件中,通过您要绑定的数据重新绑定 DataGrid。

    【讨论】:

      【解决方案3】:
       private void button2_Click(object sender, EventArgs e)//button 2 is a show data button
          {
              if (combo_floor.Text != "")
              {
      
                  DataSet ds = new DataSet();
                  string sql = "select floor_id,floor_no,floor_remark,floor_entrydate from Floorinfo where floor_no='"+combo_floor.Text+"'";
                  ds = c.select_query(sql);
                  dataGridView1.DataSource = ds.Tables["a"];
                  combo_floor.Text = "";
              }
      
              else
              {
                  showdata();
                  //showdata()is made for show all data from the given table name
              }
      
      
          }
      

      //连接在不同的类所以请不要介意

      【讨论】:

        猜你喜欢
        • 2021-03-09
        • 1970-01-01
        • 1970-01-01
        • 2012-11-05
        • 2011-09-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多