C#在其中填充datagridview和combobox

时间:2014-04-27 15:45:15

标签: c# winforms datagridview combobox

我知道如何填充datagridview,但我不知道如何根据第一个查询的值实现(同时)填充组合框。

query = "SELECT std.id, std.firstname, std.lastname, y.description
         FROM students AS std
         INNER JOIN years AS y ON y.id = std.id";
dAdapter = new OleDbDataAdapter(query, connection);
dset = new DataSet();

dAdapter.Fill(dset, "students");
dataGridView1.DataSource = dset.Tables["students"];

这可以正常工作..但datagridview中的数据都是Textbox。虽然year列应该是组合框,但由于有两个或更多项目。

    ID | Description
 ---------------------
     1 | First Grade
     2 | Second Grade

这么说,我也希望年份与查询相匹配。

ID | FirstName | LastName | Year (Combobox)
--------------------------------------------
 1     John       Lenon      Second Grade
 2     Maria      Keyl       Second Grade
 3     Stack      Overflow   First Grade

我该如何做到这一点?

编辑1: 好的,我到了某个地方。

string query = "SELECT std.id, std.std_name, std.std_last, y.id AS [yearID], y.description AS [yearDescription]" +
               "FROM students AS std " +
               "INNER JOIN years AS y ON y.id = std.year_id";
dAdapter = new OleDbDataAdapter(query, connection);
dset = new DataSet();

dAdapter.Fill(dset, "students");
dataGridView1.AutoGenerateColumns = false;
dataGridView1.DataSource = dset.Tables["students"];

var id = new DataGridViewTextBoxColumn
{
    DataPropertyName = "id",
    HeaderText = "#",
    Name = "id",
};

dataGridView1.Columns.Add(id);

DataGridViewComboBoxColumn years = new DataGridViewComboBoxColumn();

years.HeaderText = "Year";
years.DataSource = dset.Tables["students"];
years.DataPropertyName = "yearID";
years.ValueMember = "yearID";
years.DisplayMember = "yearDescription";

dataGridView1.Columns.Add(years);

这是有效的..我现在唯一的问题是,如果我将组合框索引更改为另一个,它不会改变,它会被冻结。有什么想法吗?

1 个答案:

答案 0 :(得分:0)

years.DataSource中的值应与"学生"中的值不同表

您指出ComboBox应该从哪里获得可用年限。例如,如果您只想在下拉列表中使用1998 - 2000,则可以使用如此简单的内容:

years.DataSource = new List<int>{ 1998, 1999, 2000 };

如果你想快速添加2000年到2099年之间的所有年份,你可以使用它:

years.DataSource = Enumerable.Range(2000, 100);