日期:2014-05-18  浏览次数:20908 次

datagridview 怎么根据条件设置某一行背景颜色
如根据datagridview 某一列的字段值, 如列1 = “值1” 的行 设置背景颜色 其他值得不便

------解决方案--------------------
C# code

private void dataGridView1_RowPrePaint(object sender, DataGridViewRowPrePaintEventArgs e)
        {
            if (e.RowIndex >= dataGridView1.Rows.Count - 1)
                return;
            DataGridViewRow dgr = dataGridView1.Rows[e.RowIndex];
            try
            {
              //dgr.Cells[0]是当前性别列的索引值,用以确定判断哪一列的值
                if (dgr.Cells[0].Value.ToString() == "男")
                {
                    //定义画笔,使用颜色是深灰。
                    using (SolidBrush brush = new SolidBrush(Color.DarkGray))
                    {
                        //利用画笔填充当前行
                        e.Graphics.FillRectangle(brush, e.RowBounds);
                        //将值重新写回当前行。
                        e.PaintCellsContent(e.ClipBounds); 
                        e.Handled = true;
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

        }