简体   繁体   中英

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.

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. Although the year column should be a combobox, since there are two or more items.

    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.

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.

You're indicating where the ComboBox should get its available years from. For example, if you only wanted 1998 - 2000 in the drop-down, you could use something as simple as this:

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

If you wanted to quickly add all years between, say, 2000 - 2099, you could use this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM