【发布时间】:2009-06-23 15:24:22
【问题描述】:
我有一个绑定到对象列表的 DGV。除了其中一个对象属性是布尔值并因此显示为复选框外,这工作正常,但我更喜欢简单的是/否文本字段。我考虑过添加一个额外的列并根据布尔值填充适当的字符串,但这似乎有点过头了。有没有更简单的方法?
DGV 是只读的。
【问题讨论】:
标签: .net winforms datagridview
我有一个绑定到对象列表的 DGV。除了其中一个对象属性是布尔值并因此显示为复选框外,这工作正常,但我更喜欢简单的是/否文本字段。我考虑过添加一个额外的列并根据布尔值填充适当的字符串,但这似乎有点过头了。有没有更简单的方法?
DGV 是只读的。
【问题讨论】:
标签: .net winforms datagridview
如上所述,在数据绑定场景中更改布尔值的视觉外观似乎是不可能的。 甚至 DataGridViewCellStyle.FormatProvider 也无法与 System.Int32、System.Int64、System.Decima 等类型正常工作。
因此,我找到了一个适合我的解决方法。可能这不是最好的解决方案,但目前它符合我的需求。 我处理 DataGridView.ColumnAdded 事件并将 DataGridViewCheckBoxColumn 替换为 DataGridViewTextBoxColumn。之后我使用 CellFormating 事件(微软推荐,参见上面的链接)来格式化源数据。
private DataGridViewTextBoxColumn textBoxColumn = null;
void _dataGrid_ColumnAdded(object sender, DataGridViewColumnEventArgs e)
{
// Avoid recursion
if (e.Column == textBoxColumn) return;
DataGridView gridView = sender as DataGridView;
if (gridView == null) return;
if( e.Column is DataGridViewCheckBoxColumn)
{
textBoxColumn = new DataGridViewTextBoxColumn();
textBoxColumn.Name = e.Column.Name;
textBoxColumn.HeaderText = e.Column.HeaderText;
textBoxColumn.DataPropertyName = e.Column.DataPropertyName;
gridView.Columns.Insert(e.Column.Index, textBoxColumn);
gridView.Columns.Remove(e.Column);
}
}
void _dataGrid_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
DataGridViewColumn col = _dataGrid.Columns[e.ColumnIndex];
try
{
if ( col.Name == "IsMale")
{
bool isMale = Convert.ToBoolean(e.Value);
e.Value = isMale ? "male" : "female";
}
}
catch (Exception ex)
{
e.Value = "Unknown";
}
}
【讨论】:
看来这是不可能的所以我作弊了。我向我的业务对象添加了一个只读属性,它根据布尔属性返回一个字符串。我只是在 DGV 中隐藏了布尔列并显示了字符串属性。
【讨论】:
一个有用的方法是使用 DataGridViewComboBoxColumn 将您的布尔值解码为您想要的任何字符串;它也保留了编辑值的能力,如果您确保显示值列表具有不同的首字母,它甚至可以为用户提供快捷方式(用户可以聚焦单元格并按下键盘上的单个键来更改组合选择)。
组合列不仅限于布尔值 - 任何固定的值列表、查找、枚举等都是不错的选择。这就是你可以连接一个布尔值的方式;它使用字符串/布尔元组作为组合查找/查找的后备存储:
dataGridView1.Columns.Add(new DataGridViewComboBoxColumn() {
DataPropertyName = "NameOfYourBoolColumnInYourDataTableThatTheGridIsBoundTo";
DisplayMember = "Item1", //the string in the Tuple
ValueMember = "Item2", //the bool in the Tuple
DataSource = new List<Tuple<string, bool>>() { //the list of Tuples
Tuple.Create("Yeah baby", true),
Tuple.Create("Noooo way", false)
}
});
此网格现在将显示一个组合,它曾经显示一个复选框,编辑该组合将更改主数据表中的布尔值。表中显示的值是字符串“Yeah baby”和“Nooo way”,而不是真/假,但在后端它是从主表的 bool 列读取的真假,并写回它
如果您的 datagridview 是在表单设计器中设计的,最简单的方法可能是将 DispVal 表添加到强类型数据集,然后它可以作为选择器中的“项目列表实例”使用,让您选择数据源对于组合列
【讨论】:
编辑显示布尔值的列,使 ColumnType 属性 = DataGridViewTextBoxColumn。
该列现在将显示字符串 True/False。
在设计器中进行此更改:
在设计器中,右键单击 DGV。
在弹出菜单上,选择“编辑列...”,将出现“编辑列”对话框。
在“编辑列”对话框中,选择左侧的列并在右侧找到属性(包括 ColumnType)。
您可以在将列添加到 DGV 时以编程方式设置 ColumnType:
DataGridViewColumn column = new DataGridViewColumn();
DataGridViewCell cell = new DataGridViewTextBoxCell();
column.CellTemplate = cell;
dgv.Columns.Add(column);
来自MSDN的代码。
【讨论】: