Can I change back color of gridview row which is programmatically databinding?

风流意气都作罢 提交于 2020-01-06 10:09:07

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!