Thursday, May 29, 2008

Using List View Control

If you ever wished that the Datalist control of Visual Studio 2005 could have paging enabled with it ,then it has come true but in the form of a new control named ListView.
ListView Control of Visual Studio 2008 is Quiet interesting ,Lets see how can we use this control in our project .

Now fire up Visual Studio 2008 and open a new website project .
Suppose that you have a SQL database table with three columns as First name ,Last name ,email .
Drag and drop an Sqldatasource control from the toolbox and configure it to your SQL database table .
Now drag and drop a ListView Control from the Toolbox and declare its DatasourceID to be the above datasource .
A listview control has a list of 11 Templates for configuring the Look and Feel of the listview control .But the most important part of the control is that it requires a Placeholder whose ID needs to be exactly the same as "itemplaceholder" like the code below.........

(asp:ListView ID="ListView1" runat="server" DataSourceID="SqlDataSource1")
(LayoutTemplate)
(asp:PlaceHolder ID="itemplaceholder" runat="server")(/asp:PlaceHolder)
(/LayoutTemplate)
(use the <> brackets instead of ( ) in the code )

Now add an item template to show your data like the code below ..........

(ItemTemplate )
(asp:Label ID="label1" runat="server" Text='(%#Eval("Firstname") %)'/)(br /)
(asp:Label ID="label2" runat="server" Text='(%#Eval("Lastname") %)'/)(br /)
(asp:Label ID="label3" runat="server" Text='(%#Eval("email") %)'/)(br /)
(/ItemTemplate)

You can the use other templates to make it look better.......
Now about adding the paging element to the listview control .
Drag and drop the paging control from the toolbox and set its PageControlID to the above Listview control as below ........
(asp:DataPager ID="DataPager1" runat="server" PagedControlID="ListView1"
PageSize="5")
(Fields)
(asp:NextPreviousPagerField ButtonType="Button" ShowFirstPageButton="True"
ShowLastPageButton="True" /)
(/Fields)
(/asp:DataPager)
Using this control you can set the paging style and also the number of data to be shown on the page .
The Listview control has some more intresting templates like the GroupTemplate which can be used to group data elements together but we may talk about that later in some other Blogpost.
For now you play with this new control of visual studio 2008.

No comments: