Search code examples
c#asp.netevalrepeater

How do you join individual eval items separated by comma in a repeater?


I am trying to concatenate several address entries, using a comma separator. At the moment I have this code:

<%#DataBinder.Eval(Container,"DataItem.Address1")%>,
<%#DataBinder.Eval(Container,"DataItem.Address2")%>,
<%#DataBinder.Eval(Container,"DataItem.Address3")%>, 

This code does not check for empty strings and will sometimes output things like:

Brown Lane West, , ,

I have tried the following code but it is not correct:

<%#DataBinder.Eval(Container,"DataItem.Address1") ?? ", "%>

I have also tried a null check, but it will duplicate my address

<%#String.IsNullOrEmpty(DataBinder.Eval(Container,"DataItem.Address1")) ? "" : DataBinder.Eval(Container,"DataItem.Address1") + ", "%>,

Expected result should be outputs that add a comma at the end only if the DataItem value is not null

Examples:
Brown Lane West,
Unit 14/15 Bailygate Estate, South Bailygate,
Unit 13b, Hornbeam Park Oval, Hornbeam Park,

Solution

  • I would do it like that:

    Unit 
    <%#(String.IsNullOrEmpty(Eval("Address1").ToString()) ? "" : Eval("Address1") + ",")%>
    <%#(String.IsNullOrEmpty(Eval("Address2").ToString()) ? "" : Eval("Address2") + ",")%>
    <%#(String.IsNullOrEmpty(Eval("Address3").ToString()) ? "" : Eval("Address3") + ",")%>
    

    The output looks like that:

    Unit 14/15, Bailygate Estate, South Bailygate,
    Unit 13b, Hornbeam Park Oval, Hornbeam Park,
    Unit 25, Something here,
    

    Or if you want to be even more in control of the comma:

    <%#(String.IsNullOrEmpty(Eval("Address1").ToString()) ? "" : Eval("Address1"))%><%#(String.IsNullOrEmpty(Eval("Address2").ToString()) ? "" : ", ")%><%#(String.IsNullOrEmpty(Eval("Address2").ToString()) ? "" : Eval("Address2"))%><%#(String.IsNullOrEmpty(Eval("Address3").ToString()) ? "" : ", ")%><%#(String.IsNullOrEmpty(Eval("Address3").ToString()) ? "" : Eval("Address3") + ",")%>
    

    Hope this helps.