Al2110
Al2110

Reputation: 576

DataGridView with bound DataTable - how to display ComboBox column based on values?

I have a DataGridView to which I am binding a DataTable. Let's say there are two columns. One of them is a text column, the other is a text column but should actually be a ComboBox column. Currently, the code to display the data is something like this:

DataTable usersTable = new DataTable("Users");
usersTable.Columns.Clear();
usersTable.Rows.Clear();
usersTable.Columns.Add("Username", typeof(string)); // this column is fine
usersTable.Columns.Add("User type", typeof(string)); // this column should be a ComboBox of available user types
// load the data
foreach (User u in users)
{
    usersTable.Rows.Add(u.username);
    usersTable.Rows.Add(u.usertype); // assume the database has user types of only "Admin" and "Normal"
}
// bind the data
usersDataGridView.DataSource = usersTable;

I want the DataGridView to have a column for "User type" that has comboboxes with the two available user types. How can I achieve this?

Upvotes: 1

Views: 714

Answers (1)

JohnG
JohnG

Reputation: 9479

To create the combo box column…We need two things 1) the name of the column in the grids data source we want to mate the column to (User Type). The columns DataPropertyName property is for this. 2) A collection of items we want to display to the user when the user selects the combo box.

Below, the code manually adds the items to the combo box column. In most cases you would use a DataSource.

private DataGridViewComboBoxColumn GetComboColumn() {
  DataGridViewComboBoxColumn col = new DataGridViewComboBoxColumn();
  col.Name = "UserType";
  col.DataPropertyName = "UserType";
  col.Items.Add("Admin");
  col.Items.Add("Normal");
  return col;
}

Create some data to test, and add it to the grid as a data source.

private DataTable GetDataFromDB() {
  DataTable dt = new DataTable();
  dt.Columns.Add("UserName", typeof(string));
  dt.Columns.Add("UserType", typeof(string));
  Random rand = new Random();
  string adminOrNormal;
  for (int i = 0; i < 20; i++) {
    if (rand.Next(2) == 0) {
      adminOrNormal = "Admin";
    }
    else {
      adminOrNormal = "Normal";
    }
    dt.Rows.Add("User" + i, adminOrNormal);
  }
  return dt;
}

Putting this together...

private void Form1_Load(object sender, EventArgs e) {
  dataGridView1.Columns.Add(GetComboColumn());
  dataGridView1.DataSource = GetDataFromDB();
}

Lastly, I can not stress how important it is to “check” the “User Types” in the data “BEFORE” you add the DataSource to the grid. If there is a “User Type” that does not match one of the items in the combo box, you are going to get an exception. Just a heads up.

Upvotes: 1

Related Questions