我这个datagridview没有绑定到数据源,只是显示了几行死的数据,我想单独给某一行设定颜色,这个语句是什么?
比如,我想让姓名等与“小明”的行显示兰色或者是让第2行显示兰色

解决方案 »

  1.   

    分别设置每一个列的DefaultCellStyle 属性就可以了,比如下面的代码:DataGridViewCellStyle dataGridViewCellStyle1 = new DataGridViewCellStyle();
    dataGridViewCellStyle1.Alignment = DataGridViewContentAlignment.MiddleCenter;
    dataGridViewCellStyle1.BackColor = Color.AliceBlue;
    dataGridViewCellStyle1.ForeColor = Color.Red;
    dataGridViewCellStyle1.SelectionBackColor = Color.Fuchsia;
    dataGridViewCellStyle1.SelectionForeColor = Color.Yellow;
    this.fParentDataGridViewTextBoxColumn.DefaultCellStyle = dataGridViewCellStyle1;
      

  2.   

    或者添加CellPainting事件,比如:
    private void dataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
    {
    if (e.RowIndex == 2 && e.ColumnIndex>=0)
    {
    using (SolidBrush brush = new SolidBrush(Color.Red))
    {
    e.Graphics.FillRectangle(brush, e.CellBounds);
    e.Handled = true;
    }
    }
    }
      

  3.   

    例如
    this.gridview1.ros[i].backcolor=red;
      

  4.   

    1.webform
    在DataGridView的RowDataBound事件裡判斷並修改:
    if(e.Row.Cells[n].Text=="0")
    {
       e.Row.Attributes.Add("bgColor", "red");
    }
    else if(e.Row.Cells[n].Text>"500")
    {
        e.Row.Attributes.Add("bgColor", "green");
    }
    //這裡的n是你的列qty的下標值
    2.winform
    private void dataGridView1_RowPrePaint(object sender, DataGridViewRowPrePaintEventArgs e)
            {
                if (e.RowIndex >= dataGridView1.Rows.Count - 1)
                    return;
                DataGridViewRow dgr = dataGridView1.Rows[e.RowIndex];
                try
                {
                    if (dgr.Cells["列名"].Value.ToString() == "比较值")
                    {
                        dgr.DefaultCellStyle.ForeColor = 设置的颜色;
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
      

  5.   

    //如果"小明"在第一列
    DataGridViewCellStyle style = new DataGridViewCellStyle();
    foreach(DataGridViewRow aRow in dataGridView1.Rows)
    {
    if(aRow.Cells[0].Value.ToString() == "小明")
    {
    style.BackColor=Color.Blue;
    aRow.DefaultCellStyle=style;
    }
    }