我有一些代码可以改变GridView
中特定标签的背景颜色,并且效果很好。
protected void HighLight_Hours(Label Quarter)
{
Int32 Hours;
Int32.TryParse(Quarter.Text, out Hours);
switch (Hours)
{
case 0:
Quarter.BackColor = Color.Red;
break;
case 1:
Quarter.BackColor = Color.Yellow;
break;
case 2:
Quarter.BackColor = Color.LightGreen;
break;
}
}
但是我没有为我的网格中的每个标签调用我的函数(有很多,一天中每15分钟一个),有一种方法可以循环遍历GridView
的所有内容并设置相应的颜色?
答案 0 :(得分:4)
尝试这样的事情:
protected void gv_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
// read in all controls of a row
foreach (var control in e.Row.Controls)
{
// check if the control is a label
if (control is Label)
{
// call your function and cast the control to a Label
HighLight_Hours((Label) control);
}
}
}
}
答案 1 :(得分:1)
这应该这样做:
protected void gv_OnRowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
foreach (DataControlFieldCell dcfc in e.Row.Controls)
{
DataControlFieldCell dataControlFieldCell = dcfc;
foreach(var control in dataControlFieldCell.Controls)
if (control is Label)
HighLight_Hours((Label) control);
}
}
}
答案 2 :(得分:0)
你去......
foreach (DataGridItem CurrentItem in SomeKindOfDataGrid.Items)
CurrentItem.BackColor = Color.Red;
安德鲁
答案 3 :(得分:0)
只需遍历以下事件并获得控制权,就像这样:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
foreach (GridViewRow gvr in GridView1.Rows)
{
foreach (Control ctrl in gvr.Controls)
{
Label lbl = (Label )e.Row.FindControl("yourlabel");
lbl.ForeColor =system.drawing.color.red;
}
}
}