读书人

C#中的dataGridview控件中的数据依据条

发布时间: 2013-07-09 09:50:48 作者: rapoo

C#中的dataGridview控件中的数据根据条件显示颜色
本帖最后由 pession 于 2013-06-20 08:05:35 编辑 各位好,我是C#初学者,向大家请教一下练习作业的问题
C#中的dataGridview控件中的数据颜色显示
绑定数据库中的学生成绩
显示学生成绩表时,对成绩<60用红色字体显示
>60的分级用星星显示
查找了多方资料,多次修改都不能根据成绩显示颜色,请大神帮忙看看

 
DataGridViewRow dgr = dataGridView1.Rows[3]; //假设是第三列成绩,如果是2-5列的成绩呢?
object obj=dgr.Cells[3].Value;
int i;
i=Convert.ToInt32(obj);
if (i < 60)
{
dataGridView1.Rows[3].DefaultCellStyle.ForeColor = Color.Red;
}


[解决办法]
引用:
Quote: 引用:



private void dataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
{
if (e.Value != null)
{
string s = e.Value.ToString();
if (s == "111")
{
dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Style.ForeColor = Color.Red;
}
}
}
这个没问题 你再自己检查检查

感谢你,这个方法是对的,只是没有在设计页面datagridview事件中绑定,我更改了代码显示成功了
 private void dataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
{
// int eindex = e.RowIndex + 1;
if (e.RowIndex > -1)
{
int intGrade = Convert.ToInt32(this.dataGridView1.Rows[e.RowIndex].Cells["courceNetDataGridViewTextBoxColumn"].Value);
// MessageBox.Show(intGrade.ToString())


if (intGrade < 60)
{
this.dataGridView1.Rows[e.RowIndex].Cells["courceNetDataGridViewTextBoxColumn"].Style.ForeColor = Color.Red;//设置小于60的数字显示为红色
this.dataGridView1.Rows[e.RowIndex].Cells["courceNetDataGridViewTextBoxColumn"].Style.SelectionForeColor = Color.Red;
}
}

}



依此类托 一般如果想要修改控件默认显示方式(颜色、字体、样式等等) 你可以注册一些类似CellPainting的事件 在事件处理程序中 根据条件(一般e参数可以获取想要的东西) 来自定义控件的显示方式

控件内部一般这样实现的:
// ...
DataGridViewCellPaintingEventArgs e = new DataGridViewCellPaintingEventArgs(...);
if(CellPainting != null)
{
CellPainting(this,e); //
}
//接着绘制控件
//...


你要做的:
1.注册类似CellPaiting事件
2.通过e参数判断是否满足条件
3.修改显示方式

读书人网 >C#

热点推荐