You are on page 1of 12

How to Fill a ListView with any ADO.

Net Dataset
Posted by Bill Waiblinger on October 1st, 2002

0.25 0.50 0.75 1.00 1.25 1.50 1.75 2.00 2.25 2.50 2.75 3.00 3.25 3.50 3.75 4.00 4.25 4.50 4.75 5.00

Vote!

48266010

inShare0

Environment: VB .Net, .Net Framework, SQL Server 2000 This article will show how to fill a ListView Control with the data contained in any ADO.Net DataReader. You can use a DataSet bind it to a Grid Control to show the output of a query, but data binding of controls is not the ideal method of accessing the data. A DataSet maintains a copy of the entire resultset in the client systems memory in case you need to make changes to a row. In most cases, users will be updated very few records at any given time, so holding a large resultset in memory to change one or two records is not very efficient. Imagine what the situation would be like with a user that opens multiple resultsets all the time, not bothering to close an old window until his system or the program become unstable. We all know users like that and we most plan accordingly. In addition, the DataSet will not know if the data that the user attempts to modify has been changed on the server until it posts its updates, making it difficult to control how the update conflict will be handled. Instead of using a bound grid and a DataSet, I prefer to use the listview control with the view set to details mode (.View = lvwResults in VB6) and fill it with the data from a DataReader and disposing of the DataReader as soon as the listview has been filled in. This frees up the resources involved with the DataSet and the bound control. You do have to be careful to structure your queries so that you retrieve the primary key of the table involved if you are planning on allowing updates to the data displayed.

Here is a empty listview waiting for our data. Getting the data into it works in a somewhat different manner in VB .Net than you are used to if you are moving up from previous versions of VB. With VB6, you would get a new ListItem and fill in the data by using code as shown in Example 1.
1. 2. 3. 4. 5. 6. 7. 8. 9. 'Example 1 - Creating a ListItem in VB6 'Assumes a listview control called lvwCustomers exists on form Dim lstStuff AS ListItem Set lstStuff = lvwCustomers.ListItems.Add(, ,"First Columns Output") Set lstStuff = Nothing 'End Example Code

When creating a ListItem in VB .Net, you explicity create the ListItem and then add it to the ListView's Items collection.
1. 2. 3. 4. 5. 6. 7. 8. 'Example 2 - Creating a ListItem in VB.Net 'Assumes a listview control called lvwCustomers exists on form Dim lstStuff AS ListItem = New ListViewItem() lstStuff.Text = "First Columns Output" lvwCustomers.Items.Add(lstStuff)

9. lstStuff = Nothing 10. 'End Example Code

Of course, if you only have one column of data there is no real need for a ListView control is there? Example 3 shows a more typical block of code adding a ListItem to a ListView in VB6.
1. 'Example 3 - Creating a ListItem with SubItems in VB6 2. 'Assumes a listview control called lvwCustomers exists on form 3. 4. Dim lstStuff AS ListItem 5. 6. Set lstStuff = lvwCustomers.ListItems.Add(, ,"First Columns Output") 7. 8. lstStuff.SubItems(1) = "Second Columns Output" 9. lstStuff.SubItems(2) = "Third Columns Output" 10. lstStuff.SubItems(3) = "Fourth Columns Output" 11. lstStuff.SubItems(4) = "Fifth Columns Output" 12. 13. Set lstStuff = Nothing 14. 'End Example Code

It is implicit in the code above that the Add method of the ListItems collection returns a ListItem that contains all the SubItems that the ListView's Columns collection requires. In VB .Net, things are different. We must add the SubItems to our ListItem's SubItems collection ourselves before we attach the ListItem itself to the ListView's Items collection.
1. 'Example 4 - Creating a ListItem with SubItems in VB .Net 2. 'Assumes a listview control called lvwCustomers exists on form 3. 4. Dim lstStuff AS ListItem = New ListViewItem() 5. 6. lstStuff.Text = "First Columns Output" 7. lstStuff.SubItems.Add("Second Columns Output") 8. lstStuff.SubItems.Add("Third Columns Output") 9. lstStuff.SubItems.Add("Fourth Columns Output") 10. lstStuff.SubItems.Add("Fifth Columns Output") 11. lvwCustomers.Items.Add(lstStuff) 12. 13. lstStuff = Nothing 14. 'End Example Code

Now that we know the basics of adding a ListItem to a ListView control in VB.net, lets move on to filling a ListView with data from a DataSet. The basic steps in this procedure are: 1. Clear old contents from ListView 2. Add Columns to ListView to support the Dataset 3. Fill ListView with ListItems containing the data The code for step one is pure simplicity!
1. 'clearing the contents of the ListView lvwCustomers

2. 'Note that the Clear method removes all ListItems & Columns!!! 3. lvwCustomers.Clear()

That was pretty easy, how hard can the rest of this be? Lets add the Columns to the ListView. We will accomplish this by looping through our DataSet's fields and using the names as the Column titles. Note that the columns are created and then added to the ListView's Columns collection in a very similar fashion to attaching the ListItems to the ListView. Also note that with an ADO Recordset, the Fields collection was the Default Member of the recordset. With an SqlDataReader every method acts upon the Fields collection and you can not explicity call it.
4. 'Adding the needed columns to the ListView 5. 'Using VB .Net and an ADO.Net SqlDataReader named MyData 6. 7. Dim shtFieldCntr As Short 8. Dim lvwColumn As ColumnHeader 9. 10. For shtFieldCntr = 0 To myData.FieldCount() - 1 11. 'Create Column Header 12. lvwColumn = New ColumnHeader() 13. 'Set its text to the name of the field 14. lvwColumn.Text = myData.GetName(shtFieldCntr) 15. 'add Column to ListView 16. MyListView.Columns.Add(lvwColumn) 17. Next 18. 19. lvwColumn = Nothing 20. 'End Example Code

Whew, no sweat and we are almost done. Adding the ListItems to the ListView is a simple matter of looping through the SqlDataReader's records and adding them to the ListView. To add the data to a ListItem we will use an inner loop going through the fields, creating SubItems as we go. Note the test for a Null value before putting the data in the ListItem. The ListItem will throw an exception every time you try and assign a Null value to a Text property.
21. 22. 'Adding the ListItems to the ListView with the data 'Using VB .Net and an ADO.Net SqlDataReader named MyData 23. Dim itmListItem as ListViewItem 24. Dim shtFieldCntr As Short 25. 26. Do While myData.Read 27. itmListItem = New ListViewItem() 28. 29. If myData.IsDBNull(myData(0)) Then 30. itmListItem.Text = "" 31. Else 32. itmListItem.Text = myData(0) 33. End If 34.

35. 36. 37. 38. 39. 40. 41. 42. 43. 44. 45.

For shtFieldCntr = 1 To myData.FieldCount() - 1 If myData.IsDBNull(shtFieldCntr) Then itmListItem.SubItems.Add("") Else itmListItem.SubItems.Add(myData.GetString(shtFieldCntr)) End If Next shtCntr MyListView.Items.Add(itmListItem) Loop 'End Example Code

Well, there you have it. The basics of using the ListView Control to Display a DataReaders resultset. Here is a class definition with a method called FillListView that encapsulates it all, in the tradition of OOP.
46. 47. 48. 49. 50. ' Imports System.Data.SqlClient

Public Class ListViewData Public Sub FillListView(ByRef MyListView As ListView, _ 51. ByRef myData As SqlDataReader) 52. Dim lvwColumn As ColumnHeader 53. Dim itmListItem As ListViewItem

54. 55. 56. 57. 58. 59. 60. 61. 62. 63. 64. 65. 66. 67. 68. 69. 70. 71. 72. 73. 74. 75. 76. 77. 78. 79. 80.

Dim shtCntr As Short MyListView.Clear() For shtCntr = 0 To myData.FieldCount() - 1 lvwColumn = New ColumnHeader() lvwColumn.Text = myData.GetName(shtCntr) MyListView.Columns.Add(lvwColumn) Next Do While myData.Read itmListItem = New ListViewItem() itmListItem.Text = myData(0) For shtCntr = 1 To myData.FieldCount() - 1 If myData.IsDBNull(shtCntr) Then itmListItem.SubItems.Add("") Else itmListItem.SubItems.Add(myData.GetString(shtCntr)) End If Next shtCntr MyListView.Items.Add(itmListItem) Loop End Sub End Class

Downloads
Download Complete Source Code IT Offers

Best Practices for Developing a Web Site: Checklists, Tips & Strategies. Download Exclusive eBook Now. Guide to Developing a Web Site: Best Practices, Tips and Strategies. Download Exclusive eBook Now. How to Use Facebook Safely? Social Networking Guide for IT Managers FREE with simple registration Cloud Computing: Is it a good option for your company? Download FREE eBook to Find Out. Windows 7: Pros & Cons Download eBook now with FREE and easy registration

<a href="http://o1.qnsr.com/cgi/r?WT.qs_dlk=T5jJMQrIZ2QAAAQbeVkAAAAW;;n=203;c=6517 80/651767/651748/651132/581034;s=9479;x=4864;f=8126803483;u=j;z=20120425174831" target="_blank">< img border="0" width="400" height="400" src="http://o1.qnsr.com/cgi/x?;n=203;c=651780/651767/651748/651132/581034;s=9479;x=486 4;f=8126803483;u=j;z=20120425174831" alt="Click here"></a>

Comments

thanks

Posted by data2use on 06/08/2010 04:08am it really helped me. i am sick of stupid data grid Reply

Further help needed Posted by shane99 on 01/21/2010 12:03am The provided code set is almost what I have been looking for. But since I'm an extreme newbie, I'm finding it bit difficult to do the neccessery changes here and there. My task is, once a keyword entered in a text box and click on a button to search, the list view should display the matching set of records. It could be none, one or hundred. No need of any kind of manipulations. Just the set of records should be desplayed also the scrolling should be enabled. Mine is an Access Database with one table and one column. Database name: db1 Table name: tbl1 Field name: rec1 Appreciate if someone could help me with the relevent code set. Thank you. Reply

In reverse Posted by Miroslav24 on 06/30/2009 01:25pm How can i do it in reverse? Populate database from selected item in listview. Reply

Very good Posted by Legacy on 01/15/2004 12:00am Originally posted by: Bruce Pollock
I've just started coding vb.net. Thank you for this article it helped out a great deal.

Bruce

Reply

Listview in .NET (Key property of old ListItem Control) Posted by Legacy on 11/05/2003 12:00am

Originally posted by: Kostas Hello All, I'm trying to use the .NET listview control to load a list of records and when an event occurs I want to change the checked property of a ListItem. I know the Primary Key (ID) of the record I want to change. In VB6 I did the Listview adding like this : Dim MyItem as ListItem Set MyItem=ListView1.ListItems.Add("#" & TRIM(MyID), MyText) and when I wanted to change a certain "myID" checked property I was using ListView1.ListItems("#" & MyID).Checked=True How can I do this in .NET Listview (access a certain ListItem by a Unique KEY???) Thank you in advance, Reply

Hiding columns in vb.net listview Posted by Legacy on 10/22/2003 12:00am Originally posted by: Aloysious Help me in telling me whether it is possible to hide columns and having multi line column headers. Your help is gratly appreciated Reply

on Checking the Item a Row should be Highlighted/selected Posted by Legacy on 10/13/2003 12:00am Originally posted by: Ansar In a listview if item is checked the row should be selected or highlighted how to achieve this functionality. Reply

How do you get the index of the selected item in the ListView Posted by Legacy on 10/06/2003 12:00am Originally posted by: phu Im developing a major headache in trying to figure out how to retreive the index of the selected item in the listview. If anyone has figured this out and can help, it would be greatly appreciated. Thanks. Reply

That was pretty easy, how hard can the rest of this be? Posted by Legacy on 10/05/2003 12:00am Originally posted by: chris Hallo: You write: That was pretty easy, how hard can the rest of this be? Hey, I am trying since hours to get this so easy code running. It is not so easy, considering I try it on vb.net cf. ColumnHeader and SubItems.Add seems not too work in vb.net cf. And you tell it's easy! Please consider making such comments when you tested such source code on all platforms including cb.net cf. (Or write this code will not work on cf so people do not waste their time trying it) Thanks Chris P.S. My test envirement: XDA with Armstrong Processor from British Telecom. Reply

Error in changing from SqlDataReader to OleDbDataReader

Posted by Legacy on 07/30/2003 12:00am Originally posted by: dicky After I change from SqlDataReader to OleDbDataReader in GetCustomers(), myData is not work. Pls advise. 'OleDbDataReader Private Sub GetCustomers() Dim myCon As System.Data.OleDb.OleDbConnection Dim myCmd As System.Data.OleDb.OleDbCommand = New OleDbCommand("SELECT * FROM Customers") Dim myData As System.Data.OleDb.OleDbDataReader Dim itmListItem As ListViewItem Dim lvhHelper As ListViewData = New ListViewData() 'myCon = New SqlConnection("Data Source=DevBox;Initial Catalog=Northwind;User ID=sa;Pwd=hi") myCon = New System.Data.OleDb.OleDbConnection("Provider = SQLOLEDB;Data Source=localhost;Initial Catalog=Northwind;User ID=sa") Try myCon.Open() myCmd.Connection = myCon myData = myCmd.ExecuteReader lvhHelper.FillListView(lvwCustomers, myData) myCon.Close() Catch eSql As System.Data.OleDb.OleDbException MessageBox.Show(eSql.ToString) End Try End Sub

'SqlDataReader Private Sub GetCustomers() Dim myCon As SqlConnection Dim sqlCmd As SqlCommand = New SqlCommand("SELECT * FROM Customers") Dim myData As SqlDataReader Dim itmListItem As ListViewItem Dim lvhHelper As ListViewData = New ListViewData() myCon = New SqlConnection("Data Source=localhost;Initial Catalog=Northwind;User ID=sa")

Try myCon.Open() sqlCmd.Connection = myCon myData = sqlCmd.ExecuteReader lvhHelper.FillListView(lvwCustomers, myData) myCon.Close() Catch eSql As System.Data.SqlClient.SqlException MessageBox.Show(eSql.ToString) End Try End Sub Reply

12> Loading, Please Wait ...

Leave a Comment

Your email address will not be published. All fields are required. Name Email Title

Comment

You might also like