Geeks With Blogs
Create Fun Things - Samer's Developer Blog Development Blog for C#, .NET and Obj-C

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

Posted on Tuesday, August 25, 2009 9:27 AM Quick Tips | Back to top


Comments on this post: Quick Tip: Cast DataItem in ListView to Business Object

# re: Quick Tip: Cast DataItem in ListView to Business Object
Requesting Gravatar...
Man, you are the greatest, this one has eluded me for too long and you have the simplest solution.
Left by Don on Nov 07, 2009 9:22 AM

# re: Quick Tip: Cast DataItem in ListView to Business Object
Requesting Gravatar...
Much appreciated, just what I needed...
Left by James on Mar 17, 2010 11:06 AM

# re: Quick Tip: Cast DataItem in ListView to Business Object
Requesting Gravatar...
Thank you so much.. It's the one i need indeed.
Left by Smile on Jun 07, 2010 1:08 AM

Your comment:
 (will show your gravatar)


Copyright © samerpaul | Powered by: GeeksWithBlogs.net