2015-07-10 134 views
2

在我的GridView中,我有列名Switch,它可以在每行中包含三个不同的值; L,B和T.GridView中的背景颜色

您可以根据值L,B和T关联不同的背景颜色?

例如,当行的列名称Switch中包含值L时,背景颜色为黄色,此时值B表示行背景颜色为绿色,值T表示行背景颜色为红色。

你能帮我吗?

+0

您可以在网格视图的rowdatabound事件中执行此操作。这个事件将触发每一行网格,意味着你将有权访问每行数据。因此您可以检查该值并绘制行背景颜色。 –

回答

1

你可以做这样的事情,如果电网存在于一个Windows窗体,

dataGridView1.Rows.OfType<DataGridViewRow>() 
        .Where(x => Convert.ToString(x.Cells["Switch"].Value) == "L").ToList() 
        .ForEach(x => x.DefaultCellStyle.BackColor = Color.Yellow); 

希望这有助于...

+0

你的建议应该包含在RowDataBound事件中吗? – DanielV

1

可以在RowsAdded事件试试这个

private void dataGridView1_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e) 
    { 
     var row = dataGridView1.Rows[e.RowIndex]; 
     if (String.CompareOrdinal(row.Cells["Switch"].Value.ToString(), "L") == 0) 
     { 
      row.DefaultCellStyle.BackColor = Color.Yellow; 
     } 
     else if (String.CompareOrdinal(row.Cells["Switch"].Value.ToString(), "B") == 0) 
     { 
      row.DefaultCellStyle.BackColor = Color.Blue; 
     } 
    }