2013-04-09 52 views
1

我想从组合框中检索数据并将其填充到数据网格视图中。我正在使用Visual Studio C#Windows窗体。我的应用程序使用MySql数据库检索列价格,用户和日期的数据。我试过这段代码,但它并没有填充任何数据网格视图。我在填写数据库时没有问题,但在添加要在数据网格视图中填充的组合框之后,它不起作用。在C#中 - 从组合框中选择的项目中检索数据并填充到数据网格视图

下面的代码:

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]); 
    } 
} 

表格自动加载。

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

comboProd是我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(); 
} 

此功能是没有问题的变量名仅在增加产品和进行检索例如,如果我添加Apple产品,它将保存到数据库中,并且ComboBox将检索要添加的产品Apple编辑列表中。

编辑

所以这里是我的程序流程。

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

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

但是我不确定这一行。我很怀疑。我认为这里错了。

+0

我们可以看到fillCombo方法吗?有没有抛出异常? – 2013-04-09 13:28:11

+1

另外,您正在使用comboProd.SelectedItem,但在使用fillCombo()填充组合框之前调用loadDataGridMainView_Main。这可能意味着组合框没有选定的值, – 2013-04-09 13:30:39

+0

@ Shane.C我真的不知道我在做那行代码,你可以给我更多关于该行的细节吗? – Asker626 2013-04-09 13:37:26

回答

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

刚刚更换一个声明。现在检查它。

+0

谢谢你,它也有帮助,但我仍然无法看到数据网格视图中的任何东西。 – Asker626 2013-04-09 13:46:50

+0

请注意此行comboProd.SelectedItem +“选择*从销售”我不太确定这一点。 – Asker626 2013-04-09 13:47:43

+0

为什么要用直接查询添加'comboProd.SelectedItem'? “销售”表有多少列? – Shaharyar 2013-04-09 13:50:36

0

使用DataGridViewComboBoxColumn类。设置数据源并根据需要分配ValueMember和DisplayMember列。添加obj转换为DataGridView的

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

dataGridView1.Columns.Add(dgc); 
相关问题