Exploring the ListView control in ASP.NET 3.5

Posted by: Suprotim Agarwal , on 6/5/2008, in Category ASP.NET
Views: 43131
Abstract: The ListView control is a new data control available in ASP.NET 3.5. In this article, we will just scratch the surface and explore the basic functioning of the ListView control. We will also explore how to enable Paging and Sorting on the ListView control.
Exploring the ListView control in ASP.NET 3.5
The ListView control is a new data control available in ASP.NET 3.5. If are familiar with the Gridview control or the Repeater control, you will soon realize that ListView is quiet similar to them. GridView uses row fields to display data, whereas the ListView control displays data using user-defined templates. Moreover ListView, in comparison to Repeater, contains the ability to edit and select data. In short, depending on your need, ListView allows more flexibility in displaying data, in comparison to what the GridView and Repeater does.
In one of the previous articles, we explored the new features in ASP.NET 3.5. In this article, we will just scratch the surface and explore the basic functioning of the ListView control. We will also explore how to enable Paging and Sorting on the ListView control. The more enhanced capabilities of the ListView control, will be explored in the forthcoming articles. This article assumes you have Visual Studio 2008 with web templates installed. If you have created websites in ASP.NET 2.0, the steps mentioned here will be quiet familiar. Well, so let us get started!!
Displaying content in a ListView requires you to create templates for different parts of the control. The available templates in a ListView are as follows:
Out of these templates, the Layout template and Item templates are required, when displaying data. The rest of the templates may or may not be used. The Layout template defines the root container, which contains other Item template, Group template or DataPager object. The Item Template defines the mark up needed to generate each item for each record.
Let us now walkthrough a sample where we will create a ListView control and display data in it.
Step 1: Open VS 2008. Click File > New > Website. Choose ASP.NET Website from the list of installed template, choose target platform as .NET Framework 3.5, choose the desired language and enter the location where you would like to store the website on your FileSystem. I have created a folder called VS2008 Projects, so the location over here is C:\VS 2008 Projects\ListViewDemo. After typing the location, click OK.
Step 2: Open Default.aspx. Switch to the Design mode of Default. Open the toolbox (Ctrl+Alt+X) > Data Tab > Drag and drop a ListView control to the form. If you look at the ‘Source’ view, the ListView looks as shown below:
        <asp:ListView ID="ListView1" runat="server">
We will now display data in the ListView by binding it to the datasource.
Step 3: Click on the smart tag or right click ListView > Show Smart Tag > Choose a DataSource > New Data Source… > Select Database. We will keep the default ID for SqlDataSource, SqlDataSource1 and click OK.
Step 4: On clicking Ok, you will be presented with a ‘Configure Data Source’ wizard. Click on ‘New Connection’ to open the ‘Add Connection’. Type your ‘Server Name’ and ‘Select a database Name’ to connect to. Over here, I have typed (local) as the ServerName and the database I am connecting to is Northwind. Click on ‘Test Connection’ to make sure that there are no errors connecting to the server. Click Ok.
Step 5: In your ‘Configure Data Source’, click Next. You will be displayed an option of saving the connection string to the configuration file. Select the checkbox ‘Yes, save this connection as:’ , type a name for the connectionstring ‘NorthwindConnectionString’ and click Next.
Step 6: You will be displayed the ‘Configure Select Statement’. Select ‘Specify Columns from Tables or Views’ radiobutton. Select ‘Products’ table in the Name and choose ProductID, ProductName and UnitPrice as column names as shown below:
Click Next > ‘Test Query’ to preview data > click Finish. The wizard adds a SqlDataSource control to the page and the ListView is binded to this data source.
<asp:ListView ID="ListView1" runat="server" DataSourceID="SqlDataSource1">
        <asp:SqlDataSource ID="SqlDataSource1" runat="server"
            ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString %>"
            SelectCommand="SELECT [ProductID], [ProductName], [UnitPrice] FROM [Products]">
If you check your web.config, the connection string is added as shown below:
 <addname="NorthwindConnectionString"connectionString="Data Source=(local);Initial Catalog=Northwind;Integrated Security=True"
   providerName="System.Data.SqlClient" />
Adding Paging support to the ListView
In order to add Paging to the ListView control, right click the ListView control > Show smart tag > Configure ListView. If for some reason you are not able to view the ‘Configure ListView’ option, click on ‘Refresh Schema’.
In the ‘Configure ListView’ dialog box, click on the ‘Enable Paging’ checkbox and choose ‘Numeric Pager’ from the dropdown as shown below. We will also enhance the UI of the ListView by selecting the layout as ‘Grid’ and the desired style as ‘Blues’.
Configure List View
Click Ok. Press F5 to run the application. You can test the paging functionality. If you view the source, you observe that a DataPager has been added to the source.
<asp:DataPager ID="DataPager1" runat="server">
                                    <asp:NextPreviousPagerField ButtonType="Button" ShowFirstPageButton="True"
                                        ShowNextPageButton="False" ShowPreviousPageButton="False" />
                                    <asp:NumericPagerField />
                                    <asp:NextPreviousPagerField ButtonType="Button" ShowLastPageButton="True"
                                        ShowNextPageButton="False" ShowPreviousPageButton="False" />
As already discussed in the previous article, the ListView control does not have paging capabilities. It the DataPager control that provides it with Paging capabilities. The advantage of having a separate control for paging is that you can decide the look and feel of the pager and also position it anywhere on the page. We will explore this feature in the forthcoming articles. Also note that currently the DataPager control can only be used with the ListView control.
Adding Sorting support to the ListView
P.S : Online help suggests to add Sorting by editing the Layout Template using the designer. However, I have not been able to do so from the designer. I will update this article, once I find the reason for this.
So we will be directly manipulating the source view to add sorting. Follow these steps to do so:
Step 1: Drag and drop a button control from the toolbox to the form. Change the text property of the button control to ‘Sort Product Name’ and ID property to ‘btnSort’. Then set the ‘CommandName’ property to Sort and the ‘CommandArgument’ to ‘ProductName’. The CommandArgument is set to the name of the column in the database on which sorting is to be done.
The button control would look similar to the following:
<asp:Button ID="Button1" runat="server" CommandArgument="ProductName"
            CommandName="Sort" Text="Sort Product Name" />
Step 2: Place this button control next to the DataPager control. Your source view should look like the following with the button control added :
<tr runat="server">
 <td runat="server" style="text-align: center;background-color: #5D7B9D;font-family: Verdana, Arial, Helvetica, sans-serif;color: #FFFFFF">
                            <asp:DataPager ID="DataPager1" runat="server">
                                    <asp:NextPreviousPagerField ButtonType="Button" ShowFirstPageButton="True"
                                        ShowNextPageButton="False" ShowPreviousPageButton="False" />
                                    <asp:NumericPagerField />
                                    <asp:NextPreviousPagerField ButtonType="Button" ShowLastPageButton="True"
                                        ShowNextPageButton="False" ShowPreviousPageButton="False" />
<asp:Button ID="Button1" runat="server" CommandArgument="ProductName"
                            CommandName="Sort" Text="Sort Product Name" />
That’s it. Press F5 and test the application. Click on the ‘Sort Product Name’ button to test the sorting functionality.
If you want to add sorting to the UnitPrice too, follow the same steps as discussed above. Change the text property of the button control to ‘Sort Unit Price’. Then set the ‘CommandName’ property to Sort and the ‘CommandArgument’ to ‘UnitPrice’. Similarly you can add sorting to as many columns you need following this approach.
So that was the ListView control for you. This article explored how to populate the ListView control and display data. In the articles to come, we will explore the flexibility of this control along with the DataPager control. Till then, happy coding!! I hope this article was useful and I thank you for viewing it.  
If you liked the article,  Subscribe to my RSS Feed. 

This article has been editorially reviewed by Suprotim Agarwal.

Absolutely Awesome Book on C# and .NET

C# and .NET have been around for a very long time, but their constant growth means there’s always more to learn.

We at DotNetCurry are very excited to announce The Absolutely Awesome Book on C# and .NET. This is a 500 pages concise technical eBook available in PDF, ePub (iPad), and Mobi (Kindle).

Organized around concepts, this Book aims to provide a concise, yet solid foundation in C# and .NET, covering C# 6.0, C# 7.0 and .NET Core, with chapters on the latest .NET Core 3.0, .NET Standard and C# 8.0 (final release) too. Use these concepts to deepen your existing knowledge of C# and .NET, to have a solid grasp of the latest in C# and .NET OR to crack your next .NET Interview.

Click here to Explore the Table of Contents or Download Sample Chapters!

What Others Are Reading!
Was this article worth reading? Share it with fellow developers too. Thanks!
Share on LinkedIn
Share on Google+

Suprotim Agarwal, MCSD, MCAD, MCDBA, MCSE, is the founder of DotNetCurry, DNC Magazine for Developers, SQLServerCurry and DevCurry. He has also authored a couple of books 51 Recipes using jQuery with ASP.NET Controls and The Absolutely Awesome jQuery CookBook.

Suprotim has received the prestigious Microsoft MVP award for ten consecutive times. In a professional capacity, he is the CEO of A2Z Knowledge Visuals Pvt Ltd, a digital group that offers Digital Marketing and Branding services to businesses, both in a start-up and enterprise environment.

Get in touch with him on Twitter @suprotimagarwal or at LinkedIn

Page copy protected against web site content infringement 	by Copyscape

Feedback - Leave us some adulation, criticism and everything in between!
Comment posted by nandhini on Tuesday, August 19, 2008 3:28 AM
how to create a listview control at runtime and add the layout and itemtemplate at runtiem in using c# coding?






jQuery CookBook