gpt4 book ai didi

C# 遍历 DataGridView 并更改行颜色

转载 作者:IT王子 更新时间:2023-10-29 04:29:51 25 4
gpt4 key购买 nike

我有一个由多行和多列组成的数据 GridView 。我想遍历每一行并检查特定列的内容。如果该列包含单词“NO”,我想将整行的前景色更改为红色。到目前为止,这是对一些代码的尝试,但肯定行不通,开始怀疑我是否需要遍历每个单元格?

代码:

foreach (DataGridViewRow dgvr in dataGridView1.Rows)
{
if (dgvr.Cells["FollowedUp"].Value.ToString() == ("No"))
{
dgvr.DefaultCellStyle.ForeColor = Color.Red;
}
}

最佳答案

连接OnRowDataBound事件然后做事

ASPX(网格):

    <asp:.... OnRowDataBound="RowDataBound"..../>

代码隐藏:

    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;
}
}

对于 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;
}
}
}
}

关于C# 遍历 DataGridView 并更改行颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1078782/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com