Quick Tip: Cast DataItem in ListView to Business Object

So this is one of those things that has slipped past me for all these months and now that I’ve discovered it, I can’t believe I went without it. I recently found out that I can access a business object in the ItemDataBound event of a ListView which makes it way easier to do some last minute control changing (such as binding labels or hyperlinks, etc.)

In my example, I have a LINQ to SQL class called Question. My ListView hooks up to a datasource of IEnumerable<Question> and displays its properties—nothing unusual there.

When the ListView is databound, I need to change a hyperlink to include the QuestionID (primary key) of the object as a query string, so that the user can click on it, and be linked to only that question on its own page.

What I used to do was have a label be printed inside the ListView that held the ID, find it and then use its Text value. What I discovered I could do was actually cast the ListViewItem to a ListViewDataItem and then cast that to the Question object I have:

protected void ListView1_ItemDataBound(object sender, ListViewItemEventArgs e)
    {
        if (e.Item.ItemType == ListViewItemType.DataItem)
        {
            ListViewDataItem dataItem = (ListViewDataItem)e.Item;
            Question question = (Question)dataItem.DataItem;

So now that I have the DataItem cast to a Question object, I can easily get the primary key value:

string questionID = question.QuestionID_PK.ToString();

Simple! No need to create/find label controls and pull their text value!

Note: This is a very rudimentary example of using this, since I realize I could simply use a formatted string to print out the NavigateURL of the hyperlink inside the listview, but I wanted to point out casting a DataItem to a business class object.

 

Cheers,

Samer Paul

Print | posted @ Tuesday, August 25, 2009 9:27 AM

Comments on this entry:

Gravatar # re: Quick Tip: Cast DataItem in ListView to Business Object
by Don at 11/7/2009 9:22 AM

Man, you are the greatest, this one has eluded me for too long and you have the simplest solution.
Post A Comment
Title:
Name:
Email:
Website:
Comment:
Verification: