我正在尝试将记录中的 2 或 3 个值显示到 DataGridView 的单个单元格行中。下面是一个表示数据绑定(bind)记录的类:
Class Book
{
public int BookId {get;set;}
public string Title {get;set;}
public string Publisher {get;set}
public string Author {get;set}
public Date CopyrightDate {get;set}
public byte[] BookCoverImage {get;set}
}
我希望有一个如下所示的网格:
我只对了解如何创建标题为“摘要信息”的第二列感兴趣。我一直想知道是否有一种方法可以从数据绑定(bind)源显示摘要列中的信息。现在,我在各自的列中显示每个信息,但希望在单个单元格中显示多个值,如示例图片所示。如果这可以在 WinForms DataGridView 中完成(或者也许我应该使用另一个控件?),有人可以提供有关如何完成此操作的信息或信息链接吗?提前致谢。
最佳答案
您可以使用以下任一解决方案:
- 向类添加只读摘要属性并使用绑定(bind)列。
- 使用
CellFormatting
事件为未绑定(bind)列提供值。 - 使用
CellPainting
事件自定义绘制绑定(bind)或未绑定(bind)单元格的内容。 - 使用
DataRepeater
控制。
选项 1 - 添加摘要属性
您可以添加一个新的 Summary
属性,其中包含要在单元格中显示的信息:
Class Book
{
// rest of properties ...
public string Summary
{
get
{
return
$"Title: {this.Title}\n" +
$"Author: {this.Author}\n" +
$"Copyright Date: {this.CopyrightDate}";
}
}
}
然后您可以简单地使用绑定(bind)列在 DataGridView
中显示数据。
注释1:如果模型是自动生成的,您可以将新属性放入分部类中。
注释2:如果使用DataTable
,您可以通过设置列的表达式来简单地创建公式列。
选项 2 - 单元格格式
您可以添加未绑定(bind)的列,并在运行时在 DataGridView
控件的 CellFormatting
事件中简单地提供单元格的值:
private void dgv_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
var dgv = (DataGridView)sender;
if (e.RowIndex < 0 || e.RowIndex == dgv.NewRowIndex)
return;
if (e.ColumnIndex == 1 /*The column index which you want to format*/)
{
var book = dgv.Rows[e.RowIndex].DataBoundItem as Book;
if (book != null)
e.Value =
$"Title: {book.Title}\n" +
$"Author: {book.Author}\n" +
$"Copyright Date: {book.CopyrightDate}";
}
}
选项 3 - 使用 CellPaintig
事件自定义绘制单元格
您可以在这篇文章中看到使用不同字体绘制单元格内容的示例:How can I create a footer for cell in DataGridView .
选项 4 - 使用 DataRepeater
控件
您可以使用 DataRepeater
控制。
The Visual Basic Power Packs
DataRepeater
control is a scrollable. container for controls that display repeated data, for example, rows in a database table. It can be used as an alternative to theDataGridView
control when you need more control over the layout of the data. TheDataRepeater
"repeats" a group of related controls by creating multiple instances in a scrolling view. This enables users to view several records at the same time.
关于c# - 有没有办法让 WinForms DataGridView 的列显示记录中的多个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50691908/