This article was previously published under Q316568
This article refers to the following Microsoft .NET Framework Class Library namespaces:
When you set the Sorted property of a ListBox control to True after you bind it to a datasource, you may receive the following exception:
An unhandled exception of type 'System.ArgumentException' occurred in system.windows.forms.dll.
Additional information: Can't modify the Items collection when the DataSource property is set.
To resolve this issue, set the Sorted property before you bind the ListBox to a datasource.
This behavior is by design.
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)da.Fill(ds, "cname")'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.
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.
For more information about the ListBox.Sorted property and other properties pertaining to the ListBox class, browse to the following MSDN Web sites:
Microsoft ADO.NET (included with the .NET Framework), Microsoft ADO.NET 2.0, Microsoft Visual Basic .NET 2002 Standard Edition, Microsoft Visual Basic .NET 2003 Standard Edition, Microsoft Visual Basic 2005