[英]C# populate datagridview and combobox inside of it
I know how to populate datagridview, but I'm not sure how should I implement (at same time) the fill of a combobox according to the values of the first query. 我知道如何填充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"];
This works ok..but the data inside the datagridview is all Textbox. 可以。.但是datagridview中的数据全部是Textbox。 Although the
year
column should be a combobox, since there are two or more items. 虽然
year
列应该是一个组合框,因为有两个或多个项目。
ID | Description
---------------------
1 | First Grade
2 | Second Grade
Thus said, I also would like the year to match the query. 这样说,我也希望年份能够匹配查询。
ID | FirstName | LastName | Year (Combobox)
--------------------------------------------
1 John Lenon Second Grade
2 Maria Keyl Second Grade
3 Stack Overflow First Grade
How can I accomplish this? 我该怎么做?
EDIT 1: Ok, I'm getting somewhere. 编辑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);
This works..the only problem I have now is that if I change the combobox index to another it doesn't change, it's kind of frozen. 这有效..我现在唯一的问题是,如果我将组合框索引更改为另一个不变,那就有点冻结了。 Any idea?
任何想法?
The value in years.DataSource
should be different than the "students" table. 以
years.DataSource
为单位的值应与“学生”表不同。
You're indicating where the ComboBox
should get its available years from. 您正在指示
ComboBox
应该从何处获得其可用年份。 For example, if you only wanted 1998 - 2000 in the drop-down, you could use something as simple as this: 例如,如果您只想在下拉菜单中使用1998-2000,则可以使用如下所示的简单方法:
years.DataSource = new List<int>{ 1998, 1999, 2000 };
If you wanted to quickly add all years between, say, 2000 - 2099, you could use this: 如果要快速添加2000年到2099年之间的所有年份,可以使用以下方法:
years.DataSource = Enumerable.Range(2000, 100);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.