关于Grid控件中设置行,单元格颜色

在.NET中,标准的DataGridView控件无法直接满足设置行或单元格颜色的需求。有两种解决方案:一是通过扩展DataGridView控件来实现自定义颜色功能;二是采用第三方控件,如DevExpress的GridControl,该控件提供了强大的外观定制能力,可以轻松设置每个单元格的颜色。

到面前为止,net里的DataGridView控件不能实现你的要求,如下:

        private void dataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
        
{
            
if (e.ColumnIndex == 2 && e.RowIndex != -1)  //判断所在列
            {
                DataGridViewCell cell 
= dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex];
                
int a = Convert.ToInt32(cell.Value);
                
if (a > 10)  //判断变色条件
                {
                    
//这里把整行的背景色都变了。
                    dataGridView1.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.BurlyWood;
                }

            }

        }

//想必上面的代码你很清楚,DataGridView控件无法实现你的需求,两个解决办法:
//1.自己扩展DataGridView控件,使之实现你的要求.
//2.找第三方控件.这里我用过DevExpress的GridControl控件,功能非常强大.完全可以实现这个功能,它可以直接设置每个单元格的外观.

        //using DevExpress.XtraGrid.Views.Grid;
        
//注册RowStyleChange事件
        private void gridView1_RowStyle(object sender, DevExpress.XtraGrid.Views.Grid.RowStyleEventArgs e)
        
{
            GridView view 
= sender as GridView;
            
if (e.RowHandle >= 0)
            
{
                
string category = view.GetRowCellDisplayText(e.RowHandle, view.Columns["Category"]);
                
if (category == "Beverages")
                
{
                    e.Appearance.BackColor 
= Color.Salmon;
                    e.Appearance.BackColor2 
= Color.SeaShell;
                }

            }

        }
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值