Friday, December 21, 2012

Do you know how to sort your dropBox items in C#?

Hey again, it is me posting some easy stuff about C# :) which might save you from the trouble of making these easy staff complicated.

So you have a nice dropBox with items like below ;

4 - Z
40 - A
20 - B
30 - D
4002 -AA
..
..

 DataTable dataTable= new DataTable();
 dataTable.Columns.Add("ID"); //by this way I added the first column of my dataTable.
 dataTable.Columns.Add("NAME");   // the second column of my name.
 drpOprBranchName.Items.Insert(0, "Select"); //  The first item of mine.

Then I am gonna fill in my table with data like this ; 


          for (int i = 0; i < arrayOfMine.Length; i++)
            {
                DataRow dataRow= dataTable.NewRow();
                dataRow[0] = arrayOfMine[i].code;
                dataRow[1] = arrayOfMine[i].name;
                dataTable.Rows.Add(dataRow);

            }


The first column is for ID while the second one is for some information like name . And I added a row like shonw above.  Afterwards, I've gotta feeling that I must sort the items I have :)  But first, before forgetting to add the items in my dropbox, let me show how I can add a dataTable into a dropDownList.

Here how it is ;


            DataView view= new DataView(branchNoName);
            view.Sort = " ID ASC";
            dropBox.DataSource = view; //By this way I can state that my dataView will be the source for my dropBox//
            dropBox.DataBind();



The line that is for "view.Sort = " ID ASC";" states that I would like to sort my view based on the ID Column.  However since my column was created without stating its datatype, it will be sorted as if the data of this column are "STRING"s .   But is it ? no , they are my IDs made of numbers and I would like to have an ascending sorting. If I do not specify the type of my column, it will be STRING as default.

The result I got in the first place is ;

20 - B
30 - D


4 - Z
40 - A
400001-OO
403-K
4002 -AA


See the point ? it sorts them as if they are STRING.

Thus, what I need to do is that I need to specify the type of my column as INTEGER while I create it .

dataTable.Columns.Add("ID",typeof(Int32));

By this way, my table knows that the ID column is full of integer values and can be sorted as I want.

                                                                             4 - Z


20 - B
30 - D
40 - A
403-K
4002 -AA
400001-OO






No comments:

Post a Comment