2015-11-19 32 views
2

ASP.net:如何使用中的RowDataBound一個TemplateField項目的GridView的

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

C#代碼(在RowDataDoundGridView):

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#代碼,以便它能夠確定日期是否過期。

回答

2

因爲您現在使用的是<asp:TemplateField>,所以不能再以相同的方式獲取文本。您必須找到實際的標籤控制。而不是使用e.Row.Cells,您將使用您綁定數據的標籤。

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

'DateTime.Parse(lblDue.ToString())。Date Si8

+0

你需要標籤的文字。您正在標籤控件上執行'ToString()'。 'lblDue.Text'而不是'lblDue.ToString()'。 –

+0

傻我。我沒有直截了當地想。謝謝。 – Si8

相關問題