在C#中,从组合框中的所选项目中检索数据,并填充到数据网格视图中

本文关键字:数据 填充 网格 视图 检索 数据网 选项 组合 项目 | 更新日期: 2023-09-27 18:08:19

我想从组合框中检索数据,并将其填充到数据网格视图中。我使用的是Visual Studio C#Windows窗体。我的应用程序使用MySql数据库检索列价格、用户和日期的数据。我试过这个代码,但它在数据网格视图中没有填充任何内容。一开始我填充数据库没有问题,但在我添加了要在数据网格视图中填充的组合框后,它就不起作用了。

这是代码:

public void loadDataGridView_Main()
{
    dgvMain.Rows.Clear();
    List<string>[] detailList = a.mysqlSelect(comboProd.SelectedItem + "Select * From sales");
    for (int i = 0; i < detailList.Length; i++)
    {
        dgvMain.Rows.Add(detailList[i][0], detailList[i][1], detailList[i][2], detailList[i][3]);
    }
}

以Form.自动加载

private void frmMain_Load(object sender, EventArgs e)
{
    a = new MyLibrary("localhost", "root", "", "cashieringdb");
    loadDataGridView_Main();
    dataLog();
    fillCombo();
}

comboRod是我的comboBox 的变量名

这是我的fillCombo方法我对这个没有问题

public void fillCombo()
{
    string MyConString = "SERVER=localhost;" +
                             "DATABASE=cashieringdb;" +
                                 "UID=root;" +
                              "PASSWORD='';";
    MySqlConnection connection = new MySqlConnection(MyConString);
    string command = "select productAdd from settings";
    MySqlDataAdapter da = new MySqlDataAdapter(command, connection);
    DataTable dt = new DataTable();
    da.Fill(dt);
    comboProd.DataSource = dt;
    comboProd.DisplayMember = "productAdd";
    connection.Close();
}

此功能仅用于添加产品并在ComboBox中检索,例如,如果我添加苹果产品,它将保存到数据库中,而ComboBox将检索要添加到列表中的产品苹果。

编辑

下面是我的程序流程。

在我的数据网格视图中,我有1个ComboBox和3列作为数据GridView中的字段。在ComboBox中,它将在数据库端填充我选择的项目,它将检索数据库中的任何值。这就是我这样编码的原因。

List<string>[] detailList = a.mysqlSelect(comboProd.SelectedItem + "Select * 

但我不确定这一行。我对此持怀疑态度。我认为这里有些地方错了。

在C#中,从组合框中的所选项目中检索数据,并填充到数据网格视图中

private void frmMain_Load(object sender, EventArgs e)
{
    a = new MyLibrary("localhost", "root", "", "cashieringdb");
    fillCombo();   //fill combo before calling loadDataGridView_Main()
    loadDataGridView_Main();
    dataLog();    
}

只是替换了一句话。现在检查一下。

使用DataGridViewComboBoxColumn类。根据需要设置DataSource并分配ValueMember和DisplayMember列。将obj添加到datagridview

DataGridViewComboBoxColumn dgc = new DataGridViewComboBoxColumn();
dgc.DataSource = ds;
dgc.ValueMember = "columnname1";
dgc.DisplayMember = "columnname2"
dataGridView1.Columns.Add(dgc);