我正在使用一个为不同位置硬编码列的旧应用程序,现在正在添加新位置,我决定尝试使事物动态填充。该应用程序的一个功能是,当状态被认为"不好"时,显示红色文本并保持文本。这是通过使用FindControl()"
使用TemplateFields从选定行的单元格中获取。现在我已经设置了它来使用绑定字段,那么我该如何在DataBound事件期间更改文本颜色、大小等呢?
BoundField被添加到GridView
BoundField statusField = new BoundField();
statusField.DataField = "ExceptionStatusCode";
statusField.HeaderText = "Status";
statusField.SortExpression = "ExceptionStatusCode";
this.gvView.Columns.Add(statusField);
DataBound Event For GridView
protected void gvView_DataBound(object sender, EventArgs e)
{
foreach (GridViewRow row in this.gvView.Rows)
{
//NO LONGER WORKS, NEED TO KNOW HOW TO REPRODUCE
//WHAT IS BELOW FOR BOUND FIELD
Label lblPartStatus = ((Label) row.Cells[StatusColumn].FindControl("lblPartStatus"));
if (lblPartStatus.Text == "BAD")
{
lblPartStatus.ForeColor = System.Drawing.Color.Red;
row.ToolTip = "One or more locations is missing information!";
row.BackColor = System.Drawing.Color.Salmon;
}
}
}
几年前,我写了一些代码来帮助您使用列的SortExpression, HeaderText或DataField找到单元格索引。这些年帮我省了很多力气,你就叫它myRow.Cells[myRow.GetCellIndexByFieldHandle(myDataFieldName)]
public static class Utility
{
/// <summary>
/// Gets the ordinal index of a TableCell in a rendered GridViewRow, using a text fieldHandle (e.g. the corresponding column's DataFieldName/SortExpression/HeaderText)
/// </summary>
public static int GetCellIndexByFieldHandle(this GridView grid, string fieldHandle)
{
int iCellIndex = -1;
for (int iColIndex = 0; iColIndex < grid.Columns.Count; iColIndex++)
{
if (grid.Columns[iColIndex] is DataControlField)
{
DataControlField col = (DataControlField)grid.Columns[iColIndex];
if ((col is BoundField && string.Compare(((BoundField)col).DataField, fieldHandle, true) == 0)
|| string.Compare(col.SortExpression, fieldHandle, true) == 0
|| col.HeaderText.Contains(fieldHandle))
{
iCellIndex = iColIndex;
break;
}
}
}
return iCellIndex;
}
/// <summary>
/// Gets the ordinal index of a TableCell in a rendered GridViewRow, using a text fieldHandle (e.g. the corresponding column's DataFieldName/SortExpression/HeaderText)
/// </summary>
public static int GetCellIndexByFieldHandle(this GridViewRow row, string fieldHandle)
{
return GetCellIndexByFieldHandle((GridView)row.Parent.Parent, fieldHandle);
}
}
一旦你有了单元格,我建议你通过设置Cell.CssClass
来操作它,然后使用CSS来相应地设置它的样式。避开行内样式,这是你在设置ForeColor
, BackColor
等时得到的
如果你的网格中总是有X列,你可以这样访问它们:
void grid_RowDataBound(Object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType == DataControlRowType.DataRow)
{
string text = e.Row.Cells[1].Text;
if( text.Equals("BAD") )
{
//do your stuff...
}
}
}
现在将单元格索引更改为您感兴趣的索引列。将函数附加到OnRowDataBound事件而不是OnDataBound
一个粗略的解决方案是将列索引添加到ViewState…
statusField.SortExpression = "ExceptionStatusCode";
ViewState("StatusIndex") = this.gvView.Columns.Count;
this.gvView.Columns.Add(statusField);
…然后在数据绑定
上再次使用Label lblPartStatus = ((Label) row.Cells[ViewState("StatusIndex")].FindControl("lblPartStatus"));