代码之家  ›  专栏  ›  技术社区  ›  Prateek Jahagirdar

我试图在gridview中显示过期项的背景红色,但无法使用asp.net

  •  0
  • Prateek Jahagirdar  · 技术社区  · 6 年前

    我有一个网格视图,正在绑定到我的页面加载事件上。在这里,是一个到期日列,我想用红色显示那些在30天内和30天以下到期的人。下面是我的 GridView1_RowDataBound 事件代码:

    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        string ddmmyyyy = DateTime.Now.ToString("dd-MM-yyyy");
        DateTime nowDate = Convert.ToDateTime(ddmmyyyy);//DateTime.ParseExact(ddmmyyyy, "dd-MM-yyyy", null);
        DateTime TableDate = Convert.ToDateTime(e.Row.Cells[6].Text);
        if (e.Row.RowIndex >= 0)
        {
            if (TableDate <= nowDate.AddDays(-30))
            {
                e.Row.Cells[6].BackColor = Color.Red;
            }
        }
    }
    

    这是gridview的截图。 Image 它抛出了一个例外说 the date time format is invalid . 请帮我解决这个问题。

    2 回复  |  直到 6 年前
        1
  •  0
  •   Gaurav    6 年前

    首先,gridview行数据绑定代码应该在以下条件内。尝试以下代码:

    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        string date = "30-05-2018"; //Cell value
        DateTime getdate = Convert.ToDateTime(date, System.Globalization.CultureInfo.GetCultureInfo("en-US").DateTimeFormat);
        DateTime CurrentDate = Convert.ToDateTime(DateTime.Now, System.Globalization.CultureInfo.GetCultureInfo("en-US").DateTimeFormat);
    
        if ((CurrentDate - getdate).TotalDays < 30)
        {
           e.Row.Cells[6].BackColor = System.Drawing.Color.Red;
        }
    }  
    
        2
  •  0
  •   Ravikumar    6 年前

    试试下面的代码。

    GridView1.RowDataBound += new GridViewRowEventHandler(GridView1_RowDataBound);
    
    void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            int value = (int)DataBinder.Eval(e.Row.DataItem, e.Row.Cells[2].Text); 
            // e.Row.Cells[2] references the cell value you want to use
            if (value < 100)
            {
                e.Row.Cells[2].BackColor = Color.FromName("#c6efce");
            }
            if ((value >= 100) && (value < 500))
            {
                e.Row.Cells[2].BackColor = Color.FromName("#ffeb9c");
            }
            if (value >= 500)
            {
                e.Row.Cells[2].BackColor = Color.FromName("#ffc7ce");
            }
        }
    }