删除TemplateField中的额外逗号

时间:2016-06-09 12:08:05

标签: c# asp.net

我有一个TemplateField,其中包含一些带逗号的连接项。这是为了在单个列中显示地址(存储在多个列中)。它有效,但我想删除在数据库中任何字段为空的情况下出现的额外逗号。

由于它不是字符串,我不知道该怎么做。请帮忙!

<asp:TemplateField HeaderText="Full Address">
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text="Label">
<%# Eval("claddr1") + ", " + Eval("claddr2") + ", " + Eval("claddr3") + ", " + Eval("claddr4") + ", " + Eval("claddr5") + ", " + Eval("claddr6") + ", " + Eval("clcity") + ", " + Eval("clstate") + ", " + Eval("clzip")%>
</asp:Label>                        
</ItemTemplate>
</asp:TemplateField>

1 个答案:

答案 0 :(得分:1)

您可以使用LINQ过滤掉空值,然后将其余部分加在一起:

String.Join(", ",
            new string[]{"claddr1", "claddr2",
                         "claddr3", "claddr4",
                         "claddr5", "claddr6",
                         "clcity", "clstate",
                         "clzip"}
               .Select(x => Eval(x))
               .Where(x => x!= null)
           )

我还建议将其放入代码中,以保持标记的美观和干净:

<asp:Label ID="Label1" runat="server" Text="Label">
<%# GetFormattedAddress() %>

protected string GetFormattedAddress()
{
    return String.Join(", ",
            new string[]{"claddr1", "claddr2",
                         "claddr3", "claddr4",
                         "claddr5", "claddr6",
                         "clcity", "clstate",
                         "clzip"}
               .Select(x => Eval(x))
               .Where(x => x!= null)
           );
}