问题
I have a gridview like this
<asp:GridView ID="GridView1" runat="server"
DataSourceID="SqlDataSource1">
</asp:GridView>
and I bind it on page_load
protected void Page_Load(object sender, EventArgs e)
{
SqlDataSource1.SelectCommand = "select * from table"
}
and at the table I have a field 'date'
+-----+
|date |
+-----+
|date1|
+-----+
|date2|
+-----+
and I want do that control---> if date1 < now gridviewrows backcolor = red
I did it this way
protected 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;
}
}
and this is not working, What should I do? Firstly I can't even access date. I mean the variable DateTime date is null... By the way this is not my real code, I write it for basically understanding.
回答1:
If the date1 label is in a TemplateField, the use the sample below.
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;
}
}
}
来源:https://stackoverflow.com/questions/21260558/can-i-change-back-color-of-gridview-row-which-is-programmatically-databinding