c# - DataGridView 可以用来在WinForms 中完成如下类似表格的UI 吗?

标签 c# winforms visual-studio-2010 datagridview

这一直很痛苦,但我一直在使用 TableLayoutPanel 来显示一些数据,如下面的屏幕截图所示。但有好几次有人建议使用 DataGridView 可以轻松完成

所以我的问题是,是否可以使用 DataGridView 在 Windows 窗体中完成以下屏幕截图?我在网上搜索过,但没有与以下内容类似的内容。

答案可能是“是的,可以。”“不,这是不可能的。”。但是请不要发布替代方案,因为问题的目的是最终知道这样的事情是否可以通过 DataGridView 完成。

DataTable 如下所示:

BG_Color    EmpId     ColNum    RowNum
Yellow      4304      1         1
Yellow      8464      2         1
Yellow      2012      3         1
Blue        4593      1         2
Blue        3515      2         2
Blue        0546      3         2
Green       4346      1         3
Green       5426      2         3
Green       0551      3         3

结果如下。它仅供显示,此处不可点击:

enter image description here

DataGridView 这怎么可能?我什至通过 RowNumColNum 包括了每个单元格的确切位置,以备不时之需。

或者,如果有人可以分享类似内容的链接,我们将不胜感激。

谢谢。

最佳答案

是的,您可以使用 DataGridView 创建这样的用户界面:

  • 您可以手动设置网格的RowCountColumnCount
  • 您可以处理 DataGridViewCellFormatting 事件,并在那里设置单元格的值和背景色。
  • 您不能对当前数据结构使用数据绑定(bind)。

这是一个使用您的示例数据的工作示例:

DataTable table;
private void Form1_Load(object sender, EventArgs e)
{
    table = GetData();
    this.dataGridView1.AllowUserToAddRows = false;
    this.dataGridView1.AllowUserToDeleteRows = false;
    this.dataGridView1.ReadOnly = true;
    this.dataGridView1.RowHeadersVisible = false;
    this.dataGridView1.ColumnHeadersVisible = false;
    this.dataGridView1.SelectionMode = DataGridViewSelectionMode.CellSelect;
    this.dataGridView1.RowTemplate.Height = 64;
    this.dataGridView1.CellFormatting += dataGridView1_CellFormatting;
    this.dataGridView1.ColumnCount = (int)table.Compute("Max(ColNum)", "");
    this.dataGridView1.RowCount = (int)table.Compute("Max(RowNum)", "");
}
void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
    if (e.RowIndex >= 0 & e.ColumnIndex >= 0)
    {
        var row = table.Select(string.Format("RowNum={0} AND ColNum={1}",
            e.RowIndex + 1, e.ColumnIndex + 1)).FirstOrDefault();
        if (row != null)
        {
            e.Value = row["EmpId"];
            var color = (Color)new ColorConverter().ConvertFrom(row["BG_Color"]);
            e.CellStyle.BackColor = color;
            e.CellStyle.SelectionBackColor = color;
            e.CellStyle.SelectionForeColor = Color.Black;
            e.CellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
        }
    }
}

关于c# - DataGridView 可以用来在WinForms 中完成如下类似表格的UI 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38127389/

相关文章:

c# - 如何在 C# 中锁定文件夹

c# - 读取远程文件【C#】

c# - 如何验证我分配给组合框的字典值是我认为的值?

c# - 仅当值已更改时才将值存储到数据库

visual-studio-2010 - 适用于 Windows Phone 的 PhoneGap - 文件扩展名 ".js"没有脚本引擎

visual-studio-2010 - 在 MVC++ 2010 上的 Win32 应用程序中输出到控制台/调试窗口

c# - 在基类中实现 IEquatable

c# - 未能发布 Windows 窗体项目

wpf - 如何通知 XCOPY WPF 4 应用程序的用户他需要安装 .NET 4?

c# - C#如何将一个变量名变成一个匿名对象的属性名?