Microsoft KB Archive/316568

= An &quot;An unhandled exception of type 'System.ArgumentException' occurred&quot; error occurs when you set the Sorted property to True =

Article ID: 316568

Article Last Modified on 12/6/2006

-

APPLIES TO


 * Microsoft .NET Framework 1.1 Service Pack 1
 * Microsoft ADO.NET 2.0
 * Microsoft Visual Basic .NET 2002 Standard Edition
 * Microsoft Visual Basic .NET 2003 Standard Edition
 * Microsoft Visual Basic 2005

-



This article was previously published under Q316568



This article refers to the following Microsoft .NET Framework Class Library namespaces:
 * System.Data
 * System.Data.SqlClient



SYMPTOMS
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.



RESOLUTION
To resolve this issue, set the Sorted property before you bind the ListBox to a datasource.



STATUS
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.</li>  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 &quot;General Declarations&quot; section of Form1: Imports System Imports System.Data Imports System.Data.SqlClient </li>  Copy and paste the following code in the btnTest_Click event: Dim ds As New DataSet Dim con As New SqlConnection(&quot;server=myServer;integrated security=sspi;database=northwind&quot;) Dim da As New SqlDataAdapter(&quot;select contactname from customers&quot;, con) da.Fill(ds, &quot;cname&quot;) 'ListBox1.Sorted = True 'Uncomment to sort the items. ListBox1.DataSource = ds.Tables(0) ListBox1.DisplayMember = &quot;contactname&quot; ListBox1.Sorted = True 'Comment to sort the items without error </li> Modify the connection string as appropriate for your environment.</li> Save your project. On the Debug menu, click Start to run your project.</li> Click Test.

You receive the error message described in the &quot;Symptoms&quot; section.</li> Uncomment the line after &quot;da.Fill,&quot; and then comment the last line in the code section.</li> Save and run your project.

The ListBox is sorted properly.</li></ol>

<div class="references_section">