在DataSet中对表进行排序 [英] Sort a Table in a DataSet

查看:266
本文介绍了在DataSet中对表进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个连接到我的VB.NET程序的访问数据库。本质上,我想基于列(也是主键)按升序对程序中的DataSet进行排序。我没有DataGridView中的这个表或类似的东西,我也不想。我需要这样做的原因是当一个新行添加到表时,它的行ID号等于最后一行+ 1.我添加行如下所示:

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:

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)



表中有一列QuestionNumber,其中包含值1,2,3, 4,5 ......等等。因此,我希望能够对表进行排序,使得QuestionNumber 1的行ID为0,QuestionNumber 2的行ID为1,依此类推。否则,如果Row等于0(例如),我可能会引用QuestionNumber等于2或其他的记录。



我找到的所有代码在线是指DataGridViews。 这不是我要找的!我不知道是否有我可以使用的SQL命令或者什么,但我不知道如何做到这一点。



任何帮助将不胜感激。如果这没有意义,请告诉我!


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!

推荐答案

试试这个.. :)



try this.. :)

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();


感谢Nirav。代码基本上有效!我不得不做一些修补它,因为它不完全是VB。

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



对于其他任何想知道在排序后你可以用它做什么的人,清除原始表并使用merge命令:


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:

ds.Tables(QuizName).Clear()
ds.Tables(QuizName).Merge(TempTable)


这篇关于在DataSet中对表进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆