根据ASP.NET C#中的条件更改gridview单元格的前景色 [英] Change forecolor of gridview cell based on condition in ASP.NET C#
问题描述
如果值为< = 0,我需要将gridview单元格颜色更改为红色。我已经尝试了下面的代码,它不占用每行的单元格值。
如何获取gridview的每个单元格值。
我尝试过的事情:
我正在使用下面的代码RowDataBound事件。
if(e.Row.RowType == DataControlRowType.DataRow)
{
foreach(GridViewRow) GridView1.Rows中的行)
{
for(int i = 0; i< GridView1.Columns.Count; i ++)
{
TableCell cell = row.Cells [i ]。
int quantity = int.Parse(cell.Text);
if(quantity< = 0)
{
cell.ForeColor = Color.Red;
}
}
}
}
你'非常接近...如果你想改变特定列的前景色,例如:Rate,请检查:
protected void GridView1_RowDataBound( object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
// 抓住Label Control。
Label lblRate = e.Row.FindControl( lblRate) as 标签;
// 从数据中获取此值
Double rate = Convert.ToDouble(Convert.ToString(DataBinder.Eval(e.Row.DataItem, 率跨度>)));
if (rate < =。 0 )
{
// 抓住该标签所在的单元格
DataControlFieldCell d = lblRate.Parent as DataControlFieldCell;
// 更改背景颜色
d.BackColor = System.Drawing 。红色;
// 像这样更改行颜色
e.Row.BackColor = System.Drawing.Color.LightBlue;
// 更改文本颜色
lblRate.ForeColor = System。 Drawing.Color.White;
}
}
}
有关详细信息,请参阅:如何制作Gridview行颜色/单元格颜色/文本颜色«魔鬼工作 [ ^ ]
您可能也对某种验证感兴趣:教程19:向编辑和插入接口添加验证控件 [ ^ ]
I need to change the gridview cell color to red if the value is <=0. I have tried the below piece of code and it doesn't take the cell value of each row.
How can I get each cell value of gridview.
What I have tried:
I am using the below piece of code in RowDataBound event.
if (e.Row.RowType == DataControlRowType.DataRow) { foreach (GridViewRow row in GridView1.Rows) { for (int i = 0; i < GridView1.Columns.Count; i++) { TableCell cell = row.Cells[i]; int quantity = int.Parse(cell.Text); if (quantity <= 0) { cell.ForeColor = Color.Red; } } } }
You're pretty close... If you would like to change forecolor for specific column, for example: "Rate", check this:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.DataRow) { // grab the Label Control. Label lblRate = e.Row.FindControl("lblRate") as Label; // get the value from the datasoure like this Double rate = Convert.ToDouble(Convert.ToString(DataBinder.Eval(e.Row.DataItem, "Rate"))); if (rate <= .0) { // grab the cell where that label resides DataControlFieldCell d = lblRate.Parent as DataControlFieldCell; // change the backcolor like this d.BackColor = System.Drawing.Color.Red; // change the row color like this e.Row.BackColor = System.Drawing.Color.LightBlue; // change the text color like this lblRate.ForeColor = System.Drawing.Color.White; } } }
For further details, please see: How to make a Gridview Row Color/ Cell Color/ Text Color « Devils Work[^]
You might be interested in some sort of validation too: Tutorial 19: Adding Validation Controls to the Editing and Inserting Interfaces[^]
这篇关于根据ASP.NET C#中的条件更改gridview单元格的前景色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!