tags:

views:

481

answers:

2

I am having an issue on Sorting a ListBox with a dropdown. The dropdown will have 2 options:

  1. Sort By #

  2. Sort By Type

The ListBox contains a list of items which are initially ordered in ascending order by #. It has the following format:

  1. 1: Red
  2. 2: Green
  3. 3: Blue
  4. 4: Red
  5. 5: Red

If the user choses Sort By #, it should sort in descending order if it is already in ascending order and if in ascending order if it is in descending order. If the user choses Sort By Type, it should order the colors, then #, so the above list becomes:

  1. 1: Red
  2. 4: Red
  3. 5: Red
  4. 2: Green
  5. 3: Blue

The lisbox is gets its data from an ObjectDataSource which is defined as follows:

<asp:ObjectDataSource ID="odsColors" runat="server" SelectMethod="GetColors"
        TypeName="XaiSoft.Data">  
</asp:ObjectDataSource>

I have stubbed out a method for sorting, but this is where I am stuck at, I am not sure about how to do it:

public void SortColorList()
{

}

I updated the above method to show what I am going for, but I am getting the following error:

Both DataSource and DataSourceID are defined on 'lstColors'. Remove one definition.

protected void SortColorList()
{

    XaiSoft.Data.Colors c = new XaiSoft.Data.Colors();
    DataTable dt = c.GetColorList();
    DataView dv = new DataView(dt);

    dv.Sort = "[" + dv.Table.Columns["ColorName"].ColumnName + "] asc";
    lstAuctions.DataSource = dv; //Error happens here.
    lstAuctions.DataBind();

}

I got around the error, by setting the DataSourceId = string.empty;

Thanks for the help, XaiSoft

A: 

Create a custom comparer (which implements IComparable) as described here and use that on to sort your collection appropriately. Other alternatives are also listed in that article (such as using Linq).

Gerrie Schenck
I updated the code above to show what I am going for, but I am getting an error.
Xaisoft
A: 

You mention that the lstAuctions (ListBox)'s DataSource is the odsColors ObjectDataSource, probably set on the properties of the control (at design time). In your code-behind, you bind the lstAuctions to dv (the DataView). That would seem to explain the error: "Both DataSource and DataSourceID are defined on 'lstColors'. Remove one definition." However, I do not see 'lstColors' control identified in your code. The problem could be caused by something else on the page.

Sam