Si8
Si8

Reputation: 9235

How to use a templatefield item within RowDataBound for GridView

ASP.net:

...
<asp:BoundField HeaderStyle-Width="7%" DataField="Due Date" HeaderText="Due" SortExpression="Due Date" ItemStyle-CssClass="taskTableColumn" />
...

C# code (in RowDataDound for GridView):

if (!string.IsNullOrEmpty(e.Row.Cells[4].Text)) //works correctly
{
    if (DateTime.Parse(e.Row.Cells[4].Text).Date < DateTime.Now.Date)
    {
        e.Row.ForeColor = Color.FromName("#C00000");
        e.Row.ToolTip = "Task is Past Due";
    }
    else if (DateTime.Parse(e.Row.Cells[4].Text).Date <= DateTime.Now.AddDays(inDateOffset).Date)
    {
        //e.Row.ForeColor = Color.FromName("#8A8C00");
        e.Row.ToolTip = "Task is at Risk";
    }
    else
    {
        e.Row.Cells[5].ToolTip = "Task is Not Due Yet";
    }
}

The above ASP.net/C# code worked correctly.

I had to modify the ASP.net to format the field to date:

<asp:TemplateField HeaderStyle-Width="7%" HeaderText="Due" SortExpression="Due Date" ItemStyle-CssClass="taskTableColumn">
    <ItemTemplate>
        <asp:Label ID="lblDue" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "Due Date", "{0:MM-dd-yyyy}") %>'></asp:Label>
    </ItemTemplate>
</asp:TemplateField>

Now the following line always returns a empty string: if (!string.IsNullOrEmpty(e.Row.Cells[4].Text))

How can I modify the C# code so it is able to determine if the date is past due.

Upvotes: 2

Views: 3034

Answers (1)

j.f.
j.f.

Reputation: 3949

Because you are now using an <asp:TemplateField>, you can no longer get the text the same way. You must find the actual label control. Instead of using e.Row.Cells, you'll use the label you bound the data to.

Label lblDue = (Label)e.Row.FindControl("lblDue");
if (!string.IsNullOrEmpty(lblDue.Text))
{
    ...
}

Upvotes: 2

Related Questions