[英]changing row backcolor in datagridview
我在Windows窗體中更改行顏色時遇到問題。 我用Columns做了它並為Rows嘗試了相同但它沒有用。 有人可以告訴我該怎么做嗎?
我的代碼到目前為止:
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
}
}
使用Datagridview CellPainting事件。 只需復制此代碼即可。
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;
}
if檢查是否是Header。 使用你想要的顏色..如果你不想繪制標題,只需刪除if中的所有代碼。
我想要一個漸變背色告訴我..
編輯:
這是一個代碼,用於繪制一種顏色的對行,而另一種顏色則受到損害。 你也必須使用Cellpainting活動..
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;
}
}
編輯2:細胞繪畫事件在哪里?
使用DataGridView.RowsDefaultCellStyle為所有行設置背景顏色:
dataGridView1.RowsDefaultCellStyle.BackColor = Color.Orange;
更新(如果您只想繪制一些行),您可以使用CellFormatting事件:
void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
if (e.RowIndex > 2) // condition
e.CellStyle.BackColor = Color.YellowGreen;
}
您可以在msdn上閱讀有關更改DataGridView樣式的更多信息。
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.