Additional information: Can't modify the Items collection when the DataSource property is set.
Steps to reproduce the problem
- Start Microsoft Visual Studio .NET.
- Create a new Windows application in Visual Basic .NET. Form1 is added to the project by default.
- Make sure that your project contains a reference to the System.Data namespace; if it does not, add a reference to this namespace.
- Place a Button control on Form1. Change the Name property of the button to btnTest, and then change the Text property to Test.
- Add a ListBox control to Form1.
- Use the Imports statement on the System and System.Data namespaces so that you are not required to qualify declarations in those namespaces later in your code. Add the following code to the "General Declarations" section of Form1:
- Copy and paste the following code in the btnTest_Click event:
Dim ds As New DataSet()
Dim con As New SqlConnection("server=myServer;integrated security=sspi;database=northwind")
Dim da As New SqlDataAdapter("select contactname from customers", con)
'ListBox1.Sorted = True 'Uncomment to sort the items.
ListBox1.DataSource = ds.Tables(0)
ListBox1.DisplayMember = "contactname"
ListBox1.Sorted = True 'Comment to sort the items without error
- Modify the connection string as appropriate for your environment.
- Save your project. On the Debug menu, click Start to run your project.
- Click Test.
You receive the error message described in the "Symptoms" section.
- Uncomment the line after "da.Fill," and then comment the last line in the code section.
- Save and run your project.
The ListBox is sorted properly.
Article ID: 316568 - Last Review: Mar 23, 2009 - Revision: 1