我可以更改以编程方式进行数据绑定的gridview行的背景色吗? [英] Can I change back color of gridview row which is programmatically databinding?

查看:45
本文介绍了我可以更改以编程方式进行数据绑定的gridview行的背景色吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的网格视图

<asp:GridView ID="GridView1" runat="server" 
    DataSourceID="SqlDataSource1">
</asp:GridView>

然后将其绑定到page_load

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|
+-----+

,如果date1<现在gridviewrows backcolor =红色

and I want do that control---> if date1 < now gridviewrows backcolor = red

我是这样做的

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;
    }
}

这不起作用,我该怎么办? 首先,我什至无法访问日期.我的意思是变量DateTime日期为空... 顺便一提 这不是我真正的代码,我写此代码基本上是为了理解.

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.

推荐答案

如果date1标签位于TemplateField中,请使用以下示例.

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;
            }   
    }
}

这篇关于我可以更改以编程方式进行数据绑定的gridview行的背景色吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆