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