Saturday, November 29, 2014

Formatting ListView Items

Formatting can be done either through the ASPX page or on the code behind. Below are two different instances where formatting is done.

1) Formatting the <ItemTemplate> in the Aspx page


<div class="EmployeeName">

<asp:Label ID="sampleLabel" Text='<%# String.IsNullOrEmpty(DataBinder.Eval(Container.DataItem, "employeeName").ToString()) ? "" :  DataBinder.Eval(Container.DataItem, "employeeName").ToString().PadRight(140).Substring(0,140).TrimEnd() %>'
Runat="server"/>

</div>
   
Here....I'm getting values from the database. I do, an "empty or null" check. In case the condition is true, display nothing, else display the values retrieved from the DB while restricting text  to 141 characters.                  

2) Also, you could do stuff in the code behind. Below, I limit text on item data bound.

2.1) First create a event handler

<asp:ListView ID="SearchResultsListView" runat="server" ... OnItemDataBound="employeeListView_ItemDataBound">

2.2) Then...
In the employeeListView_ItemDataBound method add the relevant code. I have added some formatting code. The FindControl() method is used to capture the label.

protected void employeeListView_ItemDataBound(object sender, ListViewItemEventArgs e)
{
            string trailer = "...";
            string tempString = string.Empty;
            Label sampleLabel;

            sampleLabel = (Label)e.Item.FindControl("sampleLabel");
            if (sampleLabel.Text.Length > 100)
            {
                tempString = sampleLabel.Text.Substring(0, 96).Trim();
                sampleLabel.Text = tempString + trailer;
            }
}


No comments:

Post a Comment