求根据单元格的值设置背景色的方法

angleoldhen 2008-03-14 03:00:05
搜索了一下,都建议在CellFormatting事件里进行编程。我现在的疑问是,在这一事件里要如何取单元格的值呢?我尝试用下面代码实现,但总是报错:
“索引超出范围。必须为非负值并小于集合大小。
参数名: index”

for(int i=0;i<dataGridView2.Rows.Count;i++)
{
if (dataGridView2.Rows[i].Cells[1].Value.ToString() == "加急")
{
e.CellStyle.BackColor = Color.Red;
e.FormattingApplied = true;
}
}


如果将Cells[1]改成Cells[0]就不会出错,但单元格也没有变色。
...全文
130 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
angleoldhen 2008-03-14
  • 打赏
  • 举报
回复
终于解决了。主要是因为从combobox取数据再写入数据库时,没有使用trim(),导致该列数据竟然后面有一堆的空格,判断后自然就不相等了,也就不变色。

另外即使考虑了trim(),dataGridView1_CellFormatting事件里的那段代码会把所有的行变色,不知道其道理,最后我做了变通,另外写了个函数:


private void makerowpink(DataGridView dgv)
{
for (int i = 0; i < dgv.Rows.Count; i++)
{
if (dgv.Rows[i].Cells["fanlulevel"].Value.ToString().Trim() == "加急")
{
dgv.Rows[i].DefaultCellStyle.BackColor = Color.Pink;
}
}
}


然后在需要展示datagridview的地方调用,总算可以实现目的。

但网上的资料基本上都是推荐用CellFormatting。怎么实现呢?

nike66 2008-03-14
  • 打赏
  • 举报
回复
this.datagridview.row[i].cells["列名"].style.BackColor = color.red;
angleoldhen 2008-03-14
  • 打赏
  • 举报
回复
总共7列。

我换成网上搜索到的方法,不会报错,但也没有变色,即使满足"加急"条件(我用messagebox.show测试过):

private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
DataGridView dgv = (DataGridView)sender;
if (dgv.Columns[e.ColumnIndex].Name == "fanlulevel" && e.Value is string)
{
string str = e.Value.ToString();
if (str == "加急")
{
dgv.DefaultCellStyle.BackColor = Color.Pink;
}
// 应用该Format,Format完毕。
e.FormattingApplied = true;
}
}


如果是用我一楼里的代码的话要放在什么事件里好呢?

for(int i=0;i<dataGridView2.Rows.Count;i++)
{
if (dataGridView2.Rows[i].Cells[1].Value.ToString() == "加急")
{
//e.CellStyle.BackColor = Color.Red;
//e.FormattingApplied = true;
//这段代码要放在什么事件里才能实现类似上面两句注释掉的语句的效果呢?
}
}

journeydj 2008-03-14
  • 打赏
  • 举报
回复
总共几列? 只有一列用1肯定会出错阿。变灰的话直接dataGridView2.Rows[i].Cells[0].style.BackColor = Color.Red;
angleoldhen 2008-03-14
  • 打赏
  • 举报
回复
winform的
purple_tide 2008-03-14
  • 打赏
  • 举报
回复
例如你的控件是 TextBox

TextBox tb= dataGridView2.Rows[i].Cells[1].FindControle("控件名字") as TextBox;

tb.Text="?????"

110,538

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧