c# - 如何在 GridView 的 RowDataBound 中使用模板字段项

标签 c# asp.net gridview

ASP.net:

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

C# 代码(在 GridViewRowDataDound 中):

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

上述 ASP.net/C# 代码工作正常。

我必须修改 ASP.net 以将字段格式化为最新日期:

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

现在以下行始终返回空字符串:if (!string.IsNullOrEmpty(e.Row.Cells[4].Text))

如何修改 C# 代码,以便它能够确定日期是否过期。

最佳答案

因为您现在使用的是<asp:TemplateField> ,您不能再以相同的方式获取文本。您必须找到实际的标签控件。而不是使用 e.Row.Cells ,您将使用将数据绑定(bind)到的标签。

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

关于c# - 如何在 GridView 的 RowDataBound 中使用模板字段项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33812570/

相关文章:

c# - 使整行在 GridView 中可点击

android - GridView.scrollTo() 的解决方法?

c# - 如何将信息附加到 DbContext 发出的每个 SqlCommand?

c# - 有什么方法可以将对象或列表传递给 sql server 存储过程?

c# - 无法访问 protected 成员 'object.MemberwiseClone()'

c# - asp.net mvc 的 ReturnUrl 问题

c# - 如何遍历 DataTable

android - 如何在Grid Layout recyclerview中实现无限滚动

c# - 为什么在 PartialView 上使用 EditorFor 在 MVC 4.5+ 中呈现局部 View

c# - 将 gridview 与我的 getall 方法绑定(bind) - Entity Framework