Windows Forms:DataGridView排序后背景颜色出现问题

本文关键字:颜色 问题 背景 Forms DataGridView 排序 Windows | 更新日期: 2023-09-27 17:58:35

我有一个Windows窗体数据网格视图,其中的行有不同的背景色

问题是,排序(单击行标题)后,背景颜色消失,所有行都是白色(默认颜色)。这个问题的原因是什么?

Windows Forms:DataGridView排序后背景颜色出现问题

根据2005年6月提交给Microsoft的错误报告,这是为Visual Studio 2005:设计的

感谢您的错误报告。这个你注意到的行为是故意的。对数据绑定网格进行排序会导致要重新创建的行(称为ListChangedType.Reset)。这会导致您的格式将丢失。你需要使用DataBindingComplete事件应用样式并检查ListChangedType.Reset知道何时运用你的造型。或者你可以使用CellFormatting事件。理想情况下,您的所有格式都可以在CellFormatting中完成它是动态应用的。

使用排序事件,您可以恢复数据网格视图的背景颜色。

private void datagridview_Sorted(object sender, EventArgs e)
{
    //you can restore backcolor of datagridview in this function.
   //example given below
    foreach (DataGridViewRow r in datagridview.Rows)
        r.DefaultCellStyle.BackColor = Color.FromArgb(220, 0, 0);            
}