C# 我可以更改正在以编程方式进行数据绑定的gridview行的背面颜色吗?
我有一个这样的网格视图C# 我可以更改正在以编程方式进行数据绑定的gridview行的背面颜色吗?,c#,asp.net,gridview,C#,Asp.net,Gridview,我有一个这样的网格视图 <asp:GridView ID="GridView1" runat="server" DataSourceID="SqlDataSource1"> </asp:GridView> 在表中,我有一个字段“日期” +-----+ |date | +-----+ |date1| +-----+ |date2| +-----+ 我想控制->如果date1
<asp:GridView ID="GridView1" runat="server"
DataSourceID="SqlDataSource1">
</asp:GridView>
在表中,我有一个字段“日期”
+-----+
|date |
+-----+
|date1|
+-----+
|date2|
+-----+
我想控制->如果date1protected void GridViewServicesList_RowDataBound(object sender, GridViewRowEventArgs e)
{
DateTime date =
Convert.ToDateTime(e.Row.Cells[indexOfDateField].Text);//returns null!!!
if(date < DateTime.Now)
{
e.Row.BackColor = Color.Red;
}
}
受保护的void GridViewServicesList\u RowDataBound(对象发送方,GridViewRowEventArgs e)
{
日期时间日期=
Convert.ToDateTime(e.Row.Cells[indexOfDateField].Text);//返回null!!!
如果(日期<日期时间.现在)
{
e、 Row.BackColor=Color.Red;
}
}
这不管用,我该怎么办?
首先,我甚至无法访问日期。我的意思是变量DateTime date为空…
顺便说一句
这不是我真正的代码,我写它基本上是为了理解。如果date1标签位于TemplateField中,请使用下面的示例
protected void GridView1_RowDataBound(object sender, System.Web.UI.WebControls.GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow) {
//Reference the date1 label in Gridviews template field
System.Web.UI.WebControls.Label date1 = (System.Web.UI.WebControls.Label)e.Row.FindControl("date1");
GridViewRow myRow = e.Row;
//set back color to green if incident category is hazard
if (date1 < DateTime.Now)
{
e.Row.BackColor = Drawing.Color.SpringGreen;
}
}
}
受保护的无效GridView1\u行数据绑定(对象发送方,System.Web.UI.WebControls.GridViewRowEventArgs e)
{
如果(e.Row.RowType==DataControlRowType.DataRow){
//在GridView模板字段中引用date1标签
System.Web.UI.WebControls.Label date1=(System.Web.UI.WebControls.Label)e.Row.FindControl(“date1”);
GridViewRow myRow=e.行;
//如果事件类别为危险,则将颜色设置为绿色
如果(date1
尝试设置单元格的背景色,而不是行的背景色,但日期为空,因此无法进行设置,我无法访问“日期”。可能我遇到了错误的事件??您确定date
为空吗?或者是否DateTime date=Convert.ToDateTime(例如,Row.Cells[indexOfDateField].Text)代码>生成错误?是的,我确信它为空。无错误。您可以在预渲染事件中通过收集和更改来进行写入。
protected void GridView1_RowDataBound(object sender, System.Web.UI.WebControls.GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow) {
//Reference the date1 label in Gridviews template field
System.Web.UI.WebControls.Label date1 = (System.Web.UI.WebControls.Label)e.Row.FindControl("date1");
GridViewRow myRow = e.Row;
//set back color to green if incident category is hazard
if (date1 < DateTime.Now)
{
e.Row.BackColor = Drawing.Color.SpringGreen;
}
}
}