我在dataGridView中显示对象列表。该列表如下:
List<IAction> actions = new List<IAction>
我在DataGridViewComboBoxColumn()上使用 karlipoppins 回答显示嵌套属性(未在IAction界面中定义)(反射)Is it possible to bind complex type properties to a datagrid?
但是如果在一种对象中没有Area属性的情况下禁用组合框我有问题
希望你能帮助我;)
在列表中有两种类型的对象:
public class MoveAction : IAction
{
public string Name { get; set; }
public bool Active { get; set; } = true;
}
public class ClickAction : IAction
{
public string Name { get; set; }
public bool Active { get; set; } = true;
public Area Area { get; set; } ////////// Additional Property
}
此附加属性对象如下所示:
public class Area
{
public string Name { get; set; }
...
}
dataGridView列定义如下:
DataGridViewComboBoxColumn CreateComboBoxWithArea()
{
DataGridViewComboBoxColumn combo = new DataGridViewComboBoxColumn();
combo.DataSource = areas.Select(t => t.Name).ToArray();
combo.DataPropertyName = "Area.Name";
combo.Name = "Area";
return combo;
}
答案 0 :(得分:0)
您可以绑定到单元格的BeginEdit
事件,并在此时取消编辑组合。像:
dataGrid.CellBeginEdit += dataGrid_CellBeginEdit;
void dgSamples_CellBeginEdit(object sender, GridViewCellCancelEventArgs e)
{
var areaObject = e.Row.Cells["Area"].Value AS Area; // .Value will be the current selected item in the cell's combo.
if (areaObject.Area == null)
{
e.Cancel = true;
}
}
这不会显示组合已被禁用&#39;但它会阻止用户降低组合并更改值。基本上使单元格只读。
最后,当您为组合框定义数据源时,我不确定您的areas
列表对象的类型。因此,当我将.Value
属性转换为Areas
时,我猜测了这种类型。您可能需要更改它。
答案 1 :(得分:0)
我找到了自己的解决方案:
在投射发件人后,我可以访问整个网格。之后,我可以用这个组合框做我想做的事情(隐藏按钮,设置只读...)。这是因为组合框没有属性bool Enable; /
感谢jaredbaszler的帮助!
private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
DataGridView grid = (DataGridView)sender;
DataGridViewRow row = grid.Rows[e.RowIndex];
DataGridViewColumn col = grid.Columns[e.ColumnIndex];
if (row.DataBoundItem != null && col.DataPropertyName.Contains("."))
{
string[] props = col.DataPropertyName.Split('.');
PropertyInfo propInfo = row.DataBoundItem.GetType().GetProperty(props[0]);
if(propInfo != null)
{
object val = propInfo.GetValue(row.DataBoundItem, null);
for (int i = 1; i < props.Length; i++)
{
propInfo = val.GetType().GetProperty(props[i]);
val = propInfo.GetValue(val, null);
}
e.Value = val;
}
else
{
DataGridViewCell cell = grid.Rows[e.RowIndex].Cells[e.ColumnIndex];
DataGridViewComboBoxCell chkCell = cell as DataGridViewComboBoxCell;
chkCell.DisplayStyle = DataGridViewComboBoxDisplayStyle.Nothing;
cell.ReadOnly = true;
}
}
}