问题
I have Problem with changing rows color in Windows Forms. I did it with Columns and tried the same for Rows but it didn't work. Can someone show me how to do it?
My Code so far:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
abc();
}
void abc()
{
DataTable hh = new DataTable();
hh.Columns.Add("1", typeof(string));
hh.Columns.Add("2", typeof(string));
hh.Columns.Add("3", typeof(string));
hh.Rows.Add(new object[] { "a", "b", "c" });
hh.Rows.Add(new object[] { "a1", "b1", "c1" });
hh.Rows.Add(new object[] { "a2", "b2", "c2" });
dataGridView1.DataSource = hh;
foreach (DataGridViewRow dr in dataGridView1.Rows) // trying to change all rows to orange
dr.DefaultCellStyle.BackColor = Color.Orange; // but it doesn't work
dataGridView1.Rows[0].DefaultCellStyle.BackColor = Color.Orange; // doesn't work
dataGridView1.Refresh();
dataGridView1.Update();
dataGridView1.Columns[0].DefaultCellStyle.BackColor = Color.Beige; // this works
}
}
回答1:
Use the Datagridview CellPainting event. Just copy this code there.
if (e.RowIndex == -1)
{
SolidBrush br= new SolidBrush(Color.Blue);
e.Graphics.FillRectangle(br, e.CellBounds);
e.PaintContent(e.ClipBounds);
e.Handled = true;
}
else
{
SolidBrush br= new SolidBrush(Color.Orange);
e.Graphics.FillRectangle(br, e.CellBounds);
e.PaintContent(e.ClipBounds);
e.Handled = true;
}
The if checks if its a Header or not. Use the colors you want.. If you don´t want to paint the header just erase all the code inside the if.
I you want a gradient backcolor tell me..
EDIT:
Here is a code to paint pair rows in one color and impairs in another. You must use the Cellpainting event too..
else
{
if (e.RowIndex % 2 == 0)
{
SolidBrush br = new SolidBrush(Color.Gainsboro);
e.Graphics.FillRectangle(br, e.CellBounds);
e.PaintContent(e.ClipBounds);
e.Handled = true;
}
else
{
SolidBrush br = new SolidBrush(Color.White);
e.Graphics.FillRectangle(br, e.CellBounds);
e.PaintContent(e.ClipBounds);
e.Handled = true;
}
}
EDIT 2: Where the cellpainting event is?
回答2:
Use DataGridView.RowsDefaultCellStyle to set background color for all rows:
dataGridView1.RowsDefaultCellStyle.BackColor = Color.Orange;
UPDATE (if you want to paint only some rows) you can use CellFormatting event:
void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
if (e.RowIndex > 2) // condition
e.CellStyle.BackColor = Color.YellowGreen;
}
You can read more about changing DataGridView styles on msdn.
回答3:
Private Sub Coloriage()
Dim fin As Integer = Gridarticles.Rows.Count - 1
Dim i As Integer
For i = 0 To fin
If Gridarticles("stock", i).Value < 0 Then
Gridarticles.Rows(i).DefaultCellStyle.BackColor = Color.Red
ElseIf Gridarticles("stock", i).Value = 0 Then
Gridarticles.Rows(i).DefaultCellStyle.BackColor = Color.Gray
End If
Next
End Sub
来源:https://stackoverflow.com/questions/14522930/changing-row-backcolor-in-datagridview