ASP Dot Net ListView DataBinding

GridView inside a ListView
ListView is a very flexible control for rendering custom formatted outputs. I have already managed it to get a horizontal menu with liquid layout. Its fantastic set of templates allows most of the rendering to be easily done. With a little bit of CSS knowledge we can avoid rendering tables for most of the lists. It is not only flexible in rendering, but also very good in handling controls inside its template. To explain this i have placed a GridView inside ItemTemplate to load in all cells. ListView ItemDataBound to load GridView
For explaining the usage of listview ItemDataBound, I have chosen a GridView to be placed in a template (fetched using findcontrol). So based on the ListView’s values the GridView will be populated. As usual, I have taken Northwind as a sample db. Further Category and products tables are selected for ListView and GridView respectively. Initially categories will be loaded into the ListView, and then Products will be loaded into the GridView contained in the respective cell of the ListView. Refer the following picture for the expected output.

Bind both ListView and GridView
I am not going to explain how to read the data into a dataset here, as it is already explained in several articles (refer category for that). For loading ListView, it is very easy as it can be directly bound to Categories table. But for the GridView, we have to wire up listview ItemDataBound event to access it. It can be accessed using the event arguments in the event listview ItemDataBound. E.Item.FindCountrol (“GridView1”) will give the Gridview1.

Access Data GridView from ListViewItem
Before fetching database values for the respective category, we have to get the GridView from the ListView. For this first the DataKeyNames has to be declared in the ListView (lets take Category ID for this sample). With this later we can access those values in the listview ItemDataBound.

DataItem DataItemIndex is not visible directly
One important item to be noted here is, unlike GridView you can not access the current row index in the ItemDataBound event directly, and you have to typecast the e.item to ListViewDataItem and then the DataItemIndex to fetch the current index.

Bind Data to GridView
To fetch the products under the specific category, we need to pass the Category ID. This can be taken from DataKeyNames as discussed earlier. Use the DataItemIndex to fetch the category ID from the DataKeyNames for the current row. After fetched the values to the DataTable just bind it to the GridView using DataSource and DataBind.

Source by Pon Saravanan

Popular Posts