【问题标题】:DataGridView with bound DataTable - how to display ComboBox column based on values?带有绑定 DataTable 的 DataGridView - 如何根据值显示 ComboBox 列?
【发布时间】:2021-03-09 22:49:43
【问题描述】:

我有一个DataGridView,我绑定了一个DataTable。假设有两列。其中一个是文本列,另一个是文本列,但实际上应该是 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" 的列,其中包含两个可用用户类型的组合框。我怎样才能做到这一点?

【问题讨论】:

  • 您需要创建一个新的DataGridViewComboBoxColumn。将其设置为DataPropertyName 以与表中的列名...“用户类型”相匹配。然后为所有“不同”“用户类型”创建一个单独的集合(表或列表),没有重复(管理员和普通等)。然后将该集合用作DataSource 到DataGridViewComboBoxColumn。然后将该列添加到网格中,然后添加网格数据源。
  • 您最可能遇到的问题是,当您将数据源添加到网格时,组合框列可能会抛出网格DataError。为了提供帮助,您需要确保数据中的所有“用户类型”都与 DataGridViewComboBoxColumns 项目集合中的用户类型之一匹配。如果没有这项检查,您将熟悉可怕的网格DataError。
  • @JohnG 你能以 sn-p 代码为例将其发布为答案吗?

标签: c# .net winforms datatable datagridview


【解决方案1】:

要创建组合框列...我们需要两件事 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 添加到网格之前“检查”数据“用户类型”的重要性。如果“用户类型”与组合框中的一项不匹配,您将获得异常。请注意。

【讨论】:

    猜你喜欢
    • 2015-11-29
    • 1970-01-01
    • 2015-07-27
    • 1970-01-01
    • 1970-01-01
    • 2012-04-15
    • 2011-05-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多