如何:设置 Windows 窗体 DataGridView 控件的交替行样式
表格数据通常以类似帐目的格式向用户显示,其中的交替行具有不同的背景色。 这种格式使用户可以更轻松地分辨每一行的单元格,尤其是有多列的宽表。
借助 DataGridView 控件,可为交替行指定完整的样式信息。 这使你可以使用背景色以及样式特性(如前景色和字体)区分交替行。
Visual Studio 中对此任务提供支持。 另请参阅如何:使用设计器设置 Windows 窗体 DataGridView 控件的交替行样式。
若要以编程方式设置交替行样式
设置 RowsDefaultCellStyle 返回的 DataGridViewCellStyle 对象的属性以及 DataGridView 的 AlternatingRowsDefaultCellStyle 属性。
this.dataGridView1.RowsDefaultCellStyle.BackColor = Color.Bisque; this.dataGridView1.AlternatingRowsDefaultCellStyle.BackColor = Color.Beige;
With Me.dataGridView1 .RowsDefaultCellStyle.BackColor = Color.Bisque .AlternatingRowsDefaultCellStyle.BackColor = Color.Beige End With
注意
使用 RowsDefaultCellStyle 和 AlternatingRowsDefaultCellStyle 属性指定的样式会重写列上以 DataGridView 级别指定的样式,但被单独的行和单元格级别上设置的样式重写。 有关详细信息,请参阅 Windows 窗体 DataGridView 控件中的单元格样式。
编译代码
此示例需要:
名为
dataGridView1
的 DataGridView 控件。对 SystemSystem.Drawing 和 System.Windows.Forms 程序集的引用。
可靠编程
为实现最大的可伸缩性,应在使用相同样式的多个行、列或单元格间共享 DataGridViewCellStyle 对象,而不是分别设置单个元素的样式属性。 有关详细信息,请参阅 缩放 Windows 窗体 DataGridView 控件的最佳做法。
另请参阅
反馈
https://aka.ms/ContentUserFeedback。
即将推出:在整个 2024 年,我们将逐步取消以“GitHub 问题”作为内容的反馈机制,并将其替换为新的反馈系统。 有关详细信息,请参阅:提交和查看相关反馈