You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#中如何实现DataGridView行交替显示棕白底色?

解决DataGridView交替行底色问题

你的代码问题在于:循环中对每一行先后设置了棕色和白色底色,后面的设置直接覆盖了前面的,所以最终所有行都显示最后一次设置的白色。

要实现交替行棕白底色的效果,有两种简单的原生方案:

方案一:通过循环判断行索引

遍历行时,根据行的索引奇偶性分配不同颜色,注意跳过自动生成的新行(如果开启了AllowUserToAddRows):

foreach (DataGridViewRow row in datagridview1.Rows)
{
    if (row.IsNewRow) continue;
    
    row.DefaultCellStyle.BackColor = row.Index % 2 == 0 ? Color.Brown : Color.White;
}

方案二:利用DataGridView自带属性(推荐)

DataGridView原生支持交替行样式设置,无需手动循环,新增行也会自动应用样式:

// 设置常规行底色
datagridview1.RowsDefaultCellStyle.BackColor = Color.Brown;
// 设置交替行底色
datagridview1.AlternatingRowsDefaultCellStyle.BackColor = Color.White;

内容的提问来源于stack exchange,提问作者WIKI

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.18 13:13:11