Winforms ComboBoxColumn值无效

时间:2016-09-27 17:24:32

标签: winforms datagridview datagridviewcombobox

我在DataGridView中使用Winforms来显示用户信息及其拥有的角色。 因为我想使用相同的网格来更新我改变的角色 DataGridViewTextBoxColumn的最后DataGridViewComboBoxColumn并设置valueMember和DataSource属性。

DataGridViewComboBoxColumn的DataSource中,我设置了Context.Role。

DataGridView的DataSource中,我使用连接设置了查询。

数据显示正常,但Combo无效。 我收到了错误

  

datagridviewcomboboxcell值无效。

这是我的代码:

var query = from u in context.User
join ur in context.UserRole on u.ID equals r.UserID
join r in context.Role on ur.RoleID.ToString() equals r.ID.ToString() 
select new
{u.ID,
u.Nick,
u.LastLogin, 
Role = ur == null ? String.Empty : r.Name
};

DataGridViewTextBoxColumn ColID = new DataGridViewTextBoxColumn();
DataGridViewTextBoxColumn ColNick = new DataGridViewTextBoxColumn();
DataGridViewTextBoxColumn ColLast = new DataGridViewTextBoxColumn();
DataGridViewComboBoxColumn ColRole = new DataGridViewComboBoxColumn();

userDataGridView.Columns.Add(ColID);
userDataGridView.Columns.Add(ColNick);
userDataGridView.Columns.Add(ColLast);
userDataGridView.Columns.Add(ColRole);

ColID.DataPropertyName = "ID";
ColNick.DataPropertyName = "Nick";
ColLast.DataPropertyName = "LastLogin";

ColRole.DataPropertyName = "Role";
ColRole.DataSource = context.Role.ToList();
ColRole.ValueMember = "ID";

userDataGridView.DataSource = query.ToList();

关于我缺少什么的想法?

1 个答案:

答案 0 :(得分:0)

首先在设置gridview数据源之前添加未绑定的comboboxColumn,为其命名,然后设置datasource,然后设置datagridview数据源。

    var query = from u in context.User
join ur in context.UserRole on u.ID equals r.UserID
join r in context.Role on ur.RoleID.ToString() equals r.ID.ToString() 
select new
{u.ID,
u.Nick,
u.LastLogin, 
Role = ur == null ? String.Empty : r.Name
};

DataGridViewTextBoxColumn ColID = new DataGridViewTextBoxColumn();
DataGridViewTextBoxColumn ColNick = new DataGridViewTextBoxColumn();
DataGridViewTextBoxColumn ColLast = new DataGridViewTextBoxColumn();
DataGridViewComboBoxColumn ColRole = new DataGridViewComboBoxColumn();

ColID.DataPropertyName = "ID";
ColNick.DataPropertyName = "Nick";
ColLast.DataPropertyName = "LastLogin";

ColRole.DataPropertyName = "Role";
ColRole.DataSource = context.Role.ToList();
ColRole.ValueMember = "ID";

userDataGridView.Columns.Add(ColID);
userDataGridView.Columns.Add(ColNick);
userDataGridView.Columns.Add(ColLast);
userDataGridView.Columns.Add(ColRole);

userDataGridView.DataSource = query.ToList();