这一直很痛苦,但我一直在使用 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
结果如下。它仅供显示,此处不可点击:
DataGridView
这怎么可能?我什至通过 RowNum
和 ColNum
包括了每个单元格的确切位置,以备不时之需。
或者,如果有人可以分享类似内容的链接,我们将不胜感激。
谢谢。
最佳答案
是的,您可以使用 DataGridView
创建这样的用户界面:
- 您可以手动设置网格的
RowCount
和ColumnCount
。 - 您可以处理
DataGridView
的CellFormatting
事件,并在那里设置单元格的值和背景色。 - 您不能对当前数据结构使用数据绑定(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/