C# 带绑定DataTable的DataGridView-如何基于值显示组合框列?
我有一个C# 带绑定DataTable的DataGridView-如何基于值显示组合框列?,c#,.net,winforms,datatable,datagridview,C#,.net,Winforms,Datatable,Datagridview,我有一个DataGridView,我要将DataTable绑定到该视图。假设有两列。其中一个是文本列,另一个是文本列,但实际上应该是组合框列。当前,显示数据的代码如下所示: DataTable usersTable = new DataTable("Users"); usersTable.Columns.Clear(); usersTable.Rows.Clear(); usersTable.Columns.Add("Username", typeof(s
DataGridView
,我要将DataTable
绑定到该视图。假设有两列。其中一个是文本列,另一个是文本列,但实际上应该是组合框列。当前,显示数据的代码如下所示:
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
中有一列用于“用户类型”
,该列包含两个可用用户类型的组合框。如何实现这一点?要创建组合框列,我们需要两件事:1)要匹配列的网格数据源中的列名称(用户类型)。列DataPropertyName
属性用于此。2) 当用户选择组合框时,我们希望向用户显示的项目集合
下面,代码手动将项目添加到组合框列。在大多数情况下,您将使用数据源
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;
}
最后,我不能强调在将
数据源添加到网格之前“检查”数据中的“用户类型”有多么重要。如果有一个“用户类型”与组合框中的一个项目不匹配,您将得到一个异常。只是提醒一下。您需要创建一个新的DataGridViewComboBoxColumn
。将其设置为DataPropertyName
以与表中的列名匹配…”“用户类型”。然后创建一个包含所有“不同”用户类型的单独集合(表或列表),不包含重复项(管理员和普通用户等)。然后将该集合用作数据源到DataGridViewComboBoxColumn
。然后将该列添加到网格,然后添加网格数据源。最有可能遇到的问题是,当您将数据源添加到网格时,组合框列可能会抛出网格DataError
。要提供帮助,您需要确保数据中的所有“用户类型”与项集合中的一个用户类型相匹配。如果没有这项检查,您将熟悉可怕的网格DataError
@JohnG您可以用一段代码作为例子来回答这个问题吗?
private void Form1_Load(object sender, EventArgs e) {
dataGridView1.Columns.Add(GetComboColumn());
dataGridView1.DataSource = GetDataFromDB();
}