How to keep a datatable from being sorted

i2kdave

New member
Joined
Mar 25, 2007
Messages
2
Programming Experience
Beginner
I'm using a data adapter to fill a datatable and the resulting table has the columns sorted alphabetically. How can I keep this from happening? I have to write the contents of the table to a txt file using nested 'For...Next' loops and it needs to be in the order it appears in the database. Thanks for any help.
 
The datatable is ordered according to how the data is dragged out of the database. If the datatable is sorted, your database is sorted, or your query has an ORDER BY clause

DataGridView shows data in a sorted way (maybe) but it does not influence the order of data in the datatable. New rows are added to the end, regardless of where they appear in the sort order..

FInally, relying on a database to return you rows in some order without specifying that order, is a very dumb idea.. If your rows need a specific order such as order-of-addition then you should add an autoincrement field or datetime field and specifically order by that..
 
I'm not concerned with the order of the rows, it's the columns I'm having trouble with. My table shows monthly rent payments for each tenant in an apartment complex, e.g. "TenantID | JanDate | JanAmountPaid | FebDate | FebAmountPaid". But when I fill my datatable and display the data in a datagrid, instead of being in the correct order, the columns are in alphabetical order. My database isn't sorted in this way, nor is there an ORDER BY clause in my SQL statement. I just don't get it.
 
I'm not concerned with the order of the rows, it's the columns I'm having trouble with. My table shows monthly rent payments for each tenant in an apartment complex, e.g. "TenantID | JanDate | JanAmountPaid | FebDate | FebAmountPaid". But when I fill my datatable and display the data in a datagrid, instead of being in the correct order, the columns are in alphabetical order. My database isn't sorted in this way, nor is there an ORDER BY clause in my SQL statement. I just don't get it.

Oh.. ehhehhe. Now you make sense :D

ORDER BY orders ROWS, not columns.. Sorry! (When you said "the columns are sorted alphabetically, I thought you meant a column of data was sorted alpha).

To change the order of columns, you must change the order of their appearance in the SQL


i.e. the following two select the same columns but a very different order:

SELECT JanDate, DecDate, FebAMount, MyCol, ZZZ, ABC FROM Table
SELECT MyCol, ZZZ, ABC, JanDate, DecDate, FebAMount FROM Table


Change the order of columns in your query, wherever it is! ANd if youre using SELECT *, then try explicitly naming them :)
 
Back
Top