Click here to Skip to main content
15,887,267 members
Please Sign up or sign in to vote.
3.00/5 (2 votes)
See more:
I have an access database connected to my VB.NET program. Essentially, I want to sort a Table within my DataSet in the program based on a column (which is also the primary key) in ascending order. I do not have this table in a DataGridView or anything like that, and I don't want to either. The reason I need to do this is when a new row is added to the Table, it has Row ID number equal to the last row + 1. I add the row as shown below:
VB
Dim cb As New OleDb.OleDbCommandBuilder(da)
Dim NewRow As DataRow
NewRow = ds.Tables(QuizName).NewRow()
NewRow.Item("QuestionNumber") = Row + 1
ds.Tables(QuizName).Rows.Add(NewRow)
da.Update(ds, QuizName)
ds.Clear()
da.Fill(ds, QuizName)

The Table has a column "QuestionNumber" which contains values of 1,2,3,4,5..... and on. Hence, I want to be able to order the Table such that QuestionNumber 1 has a row ID of 0,QuestionNumber 2 has a row ID of 1 and so on. Otherwise, if Row was equal to 0 (for example), I could be referring to the record with QuestionNumber equal to 2 or whatever.

All the code I have found online refers to DataGridViews. This is not what I am looking for! I don't know whether there is an SQL command I can use or something, but I have no idea how to do this.

Any help would be greatly appreciated. If this doesn't make sense, please tell me!
Posted

try this.. :)

C#
DataSet ds=new DataSet();
          DataTable dtTable = new DataTable();
          dtTable = ds.Tables[0];

          DataView dv = dtTable.DefaultView;



          dv.Sort = "ColumnName" + " " + "ASC";

          //OR

          dv.Sort = "ColumnName" + " " + "DESC";

          //You can pass columnname and sorting expression dynamically

          DataTable dtSorted = new DataTable();
          dtSorted = dv.ToTable();
 
Share this answer
 
Thanks Nirav. The code essentially works! I had to do a bit of tinkering with it, cause its not exactly VB.
VB
Dim TempTable As New DataTable
Dim dv As DataView
TempTable = ds.Tables(QuizName)
dv = TempTable.DefaultView
dv.Sort = "QuestionNumber ASC"
TempTable = dv.ToTable

For anyone else who is wondering what you can do with this after you have sorted it, clear the original table and use the merge command:
VB
ds.Tables(QuizName).Clear()
ds.Tables(QuizName).Merge(TempTable)
 
Share this answer
 
Comments
Nirav Prabtani 30-May-14 3:51am    
i haven't noticed that it is in vb.net so i put it in c# any ways you got your solution so cheers

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900