2


如何在不干扰当前排序顺序(不是主键)的情况下使用主键在 DataView 中定位 DataViewRow 的索引?

我有显示 DataView 内容的网格控件。
此网格中的一行被选中。当我必须更改排序时,我希望
在新的排序顺序下保留选定的行。因此,想法是
在设置新排序顺序之前获取所选 DataViewRow 的主键,并在新排序顺序下找到相同的主
键。

目前,我必须手动搜索 DataView 以获取特定的主键。
有一个更好的方法吗 ?

使用索引位置而不是主键的解决方案也可以。

4

1 回答 1

0

I think I found most appropriate way to solve this, so if anyone is interested here it is:

DataView's Find method locates row fast using current sort order. Problem with that is that sort key generally does not identify every row with unique sort key. So this to work we have to adapt sort key to be unique for every row. This could be simply accomplished by adding primary key to end of sort expression. That way all sort keys that are not unique will be additionally sorted by their primary key and that will make sort key unique and preserve sort order at the same time. Here's an example:

Let's say we have loaded DataTable:

id  last_name  first_name  date_of_birth
----------------------------------------
11  Rogers     Samuel      1968-08-17
12  Smith      John        1952-12-25
13  Johnson    Bob         1981-03-29
14  Smith      John        1977-02-08
15  Adams      David       1971-09-15
----------------------------------------

// set primary key for DataTable

table.PrimaryKey = new DataColumn[] { table.Columns[ "id" ] };

// create first sorting order by last and first name
// but make sort unique by adding primary key at end

DataView view1 = new DataView( table );
view1.Sort = "last_name, first_name, id";

// create second sorting order by date of birth and again
// make sort unique by adding primary key at end

DataView view2 = new DataView( table );
view2.Sort = "date_of_birth, id";

// get DataRow of DataTable with primary key 14

DataRow row = table.Rows.Find( 14 );

// using data from DataRow find matching sort key

// be aware that Find method of DataView could return -1
// if DataView has filter set that hides row you search

int index_in_view1 = view1.Find( new Object[] { row[ "last_name" ],
                                                row[ "first_name" ],
                                                row[ "id" ] } );

int index_in_view2 = view2.Find( new Object[] { row[ "date_of_birth" ],
                                                row[ "id" ] } );

If anyone has any objection to this solution I would really be interested to hear.

于 2013-07-29T09:57:15.437 回答