Display semicolon separated values in ASP.NET Label as new lines

Requirement:

As a part of your daily coding life at times you may have to split the input value with a value and show in newline as a read only value using a Label control.

If you come across this requirement, you can use the below code snippet. In this example I am splitting the input string with semicolon.

If your input value has any html inputs then you have to use Server.HtmlEncode when you bind the data as a new line.

Front End Code

<asp:Label ID=”lbl_PreviousApprover” runat=”server”>

<asp:Repeater ID=”rep_PreviousApprover” runat=”server”>

<ItemTemplate>

<%# Server.HtmlEncode( (string) (Container.DataItem) ) %><br />

</ItemTemplate>

</asp:Repeater>

</asp:Label>

Backend Code

List<string> list_PreviousApprover = new List<string>(((string.IsNullOrEmpty(str_Input) ? string.empty : str_Input).Split(new string[] { “;” }, StringSplitOptions.None)));

if (list_PreviousApprover.Count > 0)

{

for (int list_PreviousApprover_index = 0; list_PreviousApprover_index < list_PreviousApprover.Count; list_PreviousApprover_index++)

{

bool nullOrEmpty = string.IsNullOrEmpty(list_PreviousApprover[list_PreviousApprover_index].Trim());

if (nullOrEmpty)

{

list_PreviousApprover.RemoveAt(list_PreviousApprover_index);

–list_PreviousApprover_index;

}

}

rep_PreviousApprover.DataSource = list_PreviousApprover;

rep_PreviousApprover.DataBind();

}

else

{

lbl_PreviousApprover.Text = “-“;

}

Advertisements

About Joseph Velliah
As a SharePoint Developer my professional interests tend to be technical and SharePoint focused. I run a blog at "SP RIDER" where you can expect to read HOW TOs and scenarios that I run into during my day to day job. I hope my posts will give back a little to the community that is helped me.

Comments are closed.

%d bloggers like this: