Thursday, October 22, 2009

The BindingSource-Sort property

In this post I present an interesting conclusion about sorting a data source using the BindingSort.Sort property.

The test environment

Here is the test application I use for this presentation. Briefly, it contains a DataSet with a Test DataTable, which is the DataSource I will try so sort. Then I bind this DataSource to a ComboBox, a ListView and a DataGridView control.

The test data

As test data I use some single-char strings, added in my Test DataTable in this particular order: "V", "X", "A", "B".

C# .NET

public Form1()

{

    InitializeComponent();

 

    DataSet1.TestRow d1 = this.dataSet1.Test.NewTestRow();

    d1.Data = "V";

    this.dataSet1.Test.AddTestRow(d1);

 

    DataSet1.TestRow d2 = this.dataSet1.Test.NewTestRow();

    d2.Data = "X";

    this.dataSet1.Test.AddTestRow(d2);

 

    DataSet1.TestRow d3 = this.dataSet1.Test.NewTestRow();

    d3.Data = "A";

    this.dataSet1.Test.AddTestRow(d3);

 

    DataSet1.TestRow d4 = this.dataSet1.Test.NewTestRow();

    d4.Data = "B";

    this.dataSet1.Test.AddTestRow(d4);

}


And here is the result so far (unsorted data)...

Sorting the DataSource

What I found is that binded controls (like my ComboBox, ListView and DataGridView), act different if the BindingSource is sorted before populating the DataSource or after that. The DataSource ends up being sorted anyway, but the current selected item makes the difference.

  • Sorting before adding the data

  • C# .NET

    InitializeComponent();

     

    // A, B, >V<, X - "V" is the current item

    this.testBindingSource.Sort = "Data ASC";

     

    DataSet1.TestRow d1 = this.dataSet1.Test.NewTestRow();

    d1.Data = "V";

    this.dataSet1.Test.AddTestRow(d1);

     

    //...





  • Sorting after adding the data

  • C# .NET

    //...

     

    DataSet1.TestRow d4 = this.dataSet1.Test.NewTestRow();

    d4.Data = "B";

    this.dataSet1.Test.AddTestRow(d4);

     

    // >A<, B, V, X - "A" is the current item

    this.testBindingSource.Sort = "Data ASC";



No comments: