| « First bits of Euss 2.0 | ECMAScript vs. JavaScript » |
How to enable Listview Databinding in LayoutTemplate
I am a big fan of the ListView control in ASP.NET 3.5. Though I discovered that databinding code can't be used inside the layout template. Recently I had a simple scenario where I wanted to automatically display an arrow on the header of every sortable column.
Even the famous Matt Berseth did not manage to handle this scenario in a simple manner. If you look at the code behind, you'll see he has to handle the OnDataBinding method to check every column header and add an arrow dynamically on the sorted column.
I have found a solution which allows me to had this behavior declaratively, and even more important, simply.
Now in the layout I just have to set this binding expression:
<th class=<%# ContactsLV.SortExpression == "LastName"
? (ContactsLV.SortDirection == SortDirection.Ascending
? "sortedASC" : "sortedDESC")
: "notSorted" %>>
Where ContactLV is my listview, and LastName is the SortExpression.
To be able to handle this data binding code, the ListView has to call DataBind() on elements in the LayoutTemplate. I have created an Adapter for this purpose, and registered it in the Browser file.
The code is also really simple:
public class ListViewAdapter : ControlAdapter
{
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
((ListView)Control).DataBound += (sender, args) =>
{
if (Control != null && Control.Controls.Count > 0)
{
foreach (Control elt in Control.Controls[0].Controls)
{
if (elt is ListViewDataItem)
{
continue;
}
elt.DataBind();
}
}
};
}
}
The declaration in the BrowserFile.browser:
<browsers>
<browser refID="Default">
<controlAdapters>
<adapter controlType="System.Web.UI.WebControls.ListView"
adapterType="Microsoft.Web.Adapters.ListViewAdapter" />
</controlAdapters>
</browser>
</browsers>
And the result:
As you can see, I have used three states: notSorted, sortedASC and sortedDESC. On the image, every column not sorted has an up/down arrow, and the Title column is sorted ascending. Clicking on any other row will send a Sort command to the underlying data source, and also automatically (and magically) refresh the arrows.
Trackback address for this post
Feedback awaiting moderation
This post has 30 feedbacks awaiting moderation...