Goo*_*ber 22 c# loops datagridview row winforms
我有一个由多行和多列组成的datagridview.我想迭代每一行并检查特定列的内容.如果该列包含单词"NO",我想将整行的前景颜色更改为红色.到目前为止,这是对某些代码的尝试,但它肯定不起作用,开始怀疑我是否需要迭代每个单元格?
码:
foreach (DataGridViewRow dgvr in dataGridView1.Rows)
{
if (dgvr.Cells["FollowedUp"].Value.ToString() == ("No"))
{
dgvr.DefaultCellStyle.ForeColor = Color.Red;
}
}
Run Code Online (Sandbox Code Playgroud)
The*_*iot 25
挂起OnRowDataBound事件然后做东西
ASPX(网格):
<asp:.... OnRowDataBound="RowDataBound"..../>
Run Code Online (Sandbox Code Playgroud)
代码背后:
protected void RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowIndex == -1)
{
return;
}
if(e.Row.Cells[YOUR_COLUMN_INDEX].Text=="NO"){
e.Row.BackColor=Color.Red;
}
}
Run Code Online (Sandbox Code Playgroud)
对于WinForms:
hook the **DataBindingComplete** event and do stuff in it:
private void dataGridView1_DataBindingComplete(object sender,
DataGridViewBindingCompleteEventArgs e)
{
if (e.ListChangedType != ListChangedType.ItemDeleted)
{
DataGridViewCellStyle red = dataGridView1.DefaultCellStyle.Clone();
red.BackColor=Color.Red;
foreach (DataGridViewRow r in dataGridView1.Rows)
{
if (r.Cells["FollowedUp"].Value.ToString()
.ToUpper().Contains("NO"))
{
r.DefaultCellStyle = red;
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
在DataGridView上,处理CellFormatting事件:
dataGridView1.CellFormatting += new DataGridViewCellFormattingEventHandler(dataGridView1_CellFormatting);
Run Code Online (Sandbox Code Playgroud)
您的事件处理程序可能如下所示:
private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
if(dataGridView1.Columns[e.ColumnIndex].Name == "FollowedUp" && e.Value != null && e.Value.ToString() == "No")
dataGridView1.Rows[e.RowIndex].DefaultCellStyle.ForeColor = Color.Red;
}
Run Code Online (Sandbox Code Playgroud)
通过这种方式,您不会在行上"迭代" - 只需更改它们在网格中可见(因此需要格式化)时绘制/绘制的颜色.
public void ColourChange()
{
DataGridViewCellStyle RedCellStyle = null;
RedCellStyle = new DataGridViewCellStyle();
RedCellStyle.ForeColor = Color.Red;
DataGridViewCellStyle GreenCellStyle = null;
GreenCellStyle = new DataGridViewCellStyle();
GreenCellStyle.ForeColor = Color.Green;
foreach (DataGridViewRow dgvr in dataGridView1.Rows)
{
if (dgvr.Cells["FollowedUp"].Value.ToString().Contains("No"))
{
dgvr.DefaultCellStyle = RedCellStyle;
}
if (dgvr.Cells["FollowedUp"].Value.ToString().Contains("Yes"))
{
dgvr.DefaultCellStyle = GreenCellStyle;
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
60041 次 |
| 最近记录: |