【问题标题】:C# populate datagridview and combobox inside of itC# 在其中填充 datagridview 和组合框
【发布时间】:2014-04-27 15:45:15
【问题描述】:

我知道如何填充 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 中的数据都是文本框。虽然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);

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

【问题讨论】:

    标签: c# winforms datagridview combobox


    【解决方案1】:

    years.DataSource 中的值应该不同于“students”表。

    您指出ComboBox 应从何处获取其可用年份。例如,如果您只想在下拉列表中显示 1998 - 2000,则可以使用如下简单的内容:

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

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

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

    【讨论】:

    • 你是对的。我刚刚添加了另一个数据源及其工作。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多