繁体   English   中英

带有绑定 DataTable 的 DataGridView - 如何根据值显示 ComboBox 列?

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

我有一个绑定DataTableDataGridView 假设有两列。 其中一个是文本列,另一个是文本列,但实际上应该是ComboBox列。 目前,显示数据的代码是这样的:

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;

我希望DataGridView有一个"User type"列,其中包含两个可用用户类型的组合框。 我怎样才能做到这一点?

要创建组合框列...我们需要两件事 1) 网格数据源中列的名称,我们希望将列匹配到(用户类型)。 DataPropertyName属性就是为此。 2)当用户选择组合框时,我们希望向用户显示的项目集合。

下面,代码手动将项目添加到组合框列。 在大多数情况下,您会使用DataSource

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

创建一些数据进行测试,并将其作为数据源添加到网格中。

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;
}

把这个放在一起...

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

最后,我不能强调在将数据DataSource添加到网格之前“检查”数据中的“用户类型”是多么重要。 如果有一个“用户类型”与组合框中的一项不匹配,您将得到一个例外。 只是一个抬头。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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