【发布时间】:2021-04-09 19:21:05
【问题描述】:
我有一个数据网格视图,它可以根据通知列正确填充并为行着色。
我正在使用dataGridView1_CellFormatting 事件为行着色。
但是,当我发出隐藏列的命令时,我也会失去颜色。
dataGridView1.Columns["Notify"].Width = 0;
想使用颜色来节省网格中其他列的空间。将宽度设置为 0,即第二列仍显示该列的一部分。
当我添加 dataGridView1.Columns["Notify"].Visible = false; 时,我会丢失格式:
private void PopulateLogs()
{
var logs = logManager.GetLogRecordsByDay(selectedDay);
dataGridView1.DataSource = logs;
dataGridView1.AllowUserToAddRows = false;
dataGridView1.AllowUserToDeleteRows = false;
dataGridView1.AllowUserToResizeRows = false;
dataGridView1.Columns["Id"].Visible = false;
dataGridView1.Columns["Notify"].Visible = false;
dataGridView1.Columns["LogDateTime"].DefaultCellStyle.Format = "HH:mm";
dataGridView1.Columns["LogDateTime"].Width = 20;
dataGridView1.Columns["LogEntry"].Width = 100;
dataGridView1.Columns["Analyst"].Width = 15;
dataGridView1.AllowUserToAddRows = false;
}
private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
if (this.dataGridView1.Columns[e.ColumnIndex].Name == "Notify")
{
if (e.Value != null)
{
string stringValue = (string)e.Value;
stringValue = stringValue.ToLower();
if ((stringValue.IndexOf("1") > -1))
{
this.dataGridView1.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.MistyRose;
}
}
}
}
【问题讨论】:
-
如果你隐藏一个列(设置它
Visible = false),你不会丢失它。它仍然存在,并且可以访问相关的单元格。 -
我更新了我的问题,当我添加 dataGridView1.Columns["Notify"].Visible = false;格式随列消失。
-
我会使用
RowPrePaint事件,但通常当您的代码不起作用时,您需要发布代码而不是关于代码的故事。 -
您不是在处理
CellFormatting来更改行的颜色吗? 他的格式如何在没有通知的情况下消失?您正在应用格式,因此您的代码有效或无效。只需发布该代码。 -
因此,您正在检查是否正在格式化不可见的单元格。该列在不可见时可能仅格式化一次。正如建议的那样,使用
RowPrePaint或RowPostPaint事件,因为您处理的是行的属性,而不是每个单元格的属性(CellFormatting被提高了无数次)。只需根据dataGridView1["Notify", e.RowIndex].Value.ToString().Equals("0")设置颜色即可。
标签: c# winforms datagridview