我有一个像这样的Gridview:
我需要检查最后一列日期,如果比今天更早,则更改前景色。
我试过这样:
DateTime dt;
string today = DateTime.Now.ToString("dd.MM.yyyy");
int lastcol = e.Row.Cells.Count - 1;
if (DateTime.TryParseExact(e.Row.Cells[lastcol].Text, "dd.MM.yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out dt))
{
string dtstr = dt.ToString("dd.MM.yyyy");
if (dtstr != today)
{
e.Row.Cells[lastcol].ForeColor = System.Drawing.Color.Red;
}
}
它正在为这样的列名工作(我知道因为DateTime Tryparse ......):
我需要更改最后一列的每个单元格的前景色(如果比今天更早):
我该怎么做?
答案 0 :(得分:2)
这没效果?
DateTime dt;
GridView myGrid = new GridView();
GridViewRow e = myGrid.SelectRow(0);
int lastcol = e.Row.Cells.Count - 1;
if (DateTime.TryParseExact(e.Row.Cells[lastcol].Text, "dd.MM.yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out dt))
{
if (dt > DateTime.Now)
{
for each(GridViewRow current in myGrid.Rows)
{
current.Cells[lastcol].ForeColor = System.Drawing.Color.Red;
}
}
}
答案 1 :(得分:0)
好吧,如果你做了一个会做事情的foreach:
Well if you make a foreach that will do the thing :
DateTime dt;
string today = DateTime.Now.ToString("dd.MM.yyyy");
int lastcol = e.Row.Cells.Count - 1;
if (DateTime.TryParseExact(e.Row.Cells[lastcol].Text, "dd.MM.yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out dt))
{
string dtstr = dt.ToString("dd.MM.yyyy");
if (dtstr != today)
{
foreach (Gridview a in idGridView.Rows)
{
a.Cells[7].ForeColor = System.Drawing.Color.Red
}
}
}
答案 2 :(得分:0)
尝试在RowDataBound事件中创建
protected void GridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Cells[GetColumnIndexByName(e.Row, "yourDate")].ForeColor = System.Drawing.Color.Red ;
}
}
使用此halper方法
int GetColumnIndexByName(GridViewRow row, string SearchColumnName)
{
int columnIndex = 0;
foreach (DataControlFieldCell cell in row.Cells)
{
if (cell.ContainingField is BoundField)
{
if (((BoundField)cell.ContainingField).DataField.Equals(SearchColumnName))
{
break;
}
}
columnIndex++;
}
return columnIndex;
}
答案 3 :(得分:0)
这样做。
if (DateTime.TryParseExact(e.Row.Cells[lastcol].Text, "dd.MM.yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out dt))
{
string dtstr = dt.ToString("dd.MM.yyyy");
if (dtstr != today)
{
e.Row.Cells[lastcol].ForeColor = System.Drawing.Color.Red;
foreach (GridViewRow row in GridView1.Rows)
{
row.Cells[lastcol].ForeColor = System.Drawing.Color.Red;
}
}
}