[英]How to set the background color for specified row in datagridview?
我想為datagridview中的指定行設置背景色。我需要一個for循環(i=0;i<10;i++)
這個for循環中,我將邏輯寫為
if(i=1)
{
//Want to Set Color For This Specified Row..
dataGridView1.SelectedRows[1].DefaultCellStyle.SelectionBackColor = Color.Yellow;
}
if(i=1)
{
//Want to Set Color For This Specified Row..
dataGridView1.SelectedRows[2].DefaultCellStyle.SelectionBackColor = Color.Blue;
}
if(i=1)
{
//Want to Set Color For This Specified Row..
dataGridView1.SelectedRows[3].DefaultCellStyle.SelectionBackColor = Color.Red;
}
但是我沒有得到預期的收益。 希望你理解我的需要。 請幫我。
代替使用DataGridview的SelectedRows
屬性,可以按以下方式使用
dataGridView1.Rows[1].DefaultCellStyle.ForeColor = Color.Red;
因為SelectedRows
屬性將僅在用戶選擇行時返回行,所以如果未選擇任何行,則您的代碼將引發異常。
編輯:
對此您有疑問,請提供示例代碼,希望對您有所幫助。
for (int i = 0; i < 10; i++)
{
if (dataGridView1.Rows.Count > i)
{
if (i == 1)
dataGridView1.Rows[i].DefaultCellStyle.ForeColor = Color.Red;
else if (i == 2)
dataGridView1.Rows[i].DefaultCellStyle.ForeColor = Color.Blue;
else
dataGridView1.Rows[i].DefaultCellStyle.ForeColor = Color.Green;
}
}
您可以處理數據網格的不同事件並設置單元格樣式
這是相關問題的例子
private void dgvStatus_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
if (e.ColumnIndex != color.Index)
return;
e.CellStyle.BackColor = Color.Red;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.