DataGrid索引问题

通过DataGrid.CurrentRowIndex是可以取到焦点所在当前行的索引,不过,如果点击某列的标题,排序,索引就会发生变化
这个时候要怎么办呢?

该问题产生的原因在于当DataGrid重新排序后,相应的DataTable是保持不变的,重新进行排序的其实是相应的DataView(您可以通过DataView.Sort得到当前的排序)。因此,要取得  
  重新排序后的DataGrid的某一行的数据不能简单的取DataTable中该行的值(实际上这两行并不对应),而应该和DataView关联或者是通过其他的途径。  
   
   
   
  DataView   dv=new   DataView(dataset.table1);    
  datagrid.DataSource=dv;    
  ...  
   
  DataRow   currentRow   =   dataView[dataGrid1.CurrentRowIndex].Row;  
  可以取到DataGrid的当前行。  
   
  另一种方法是通过CurrencyManager来取得当前行:  
  CurrencyManager   cm   =   (CurrencyManager)  
  BindingContext[dataGrid.DataSource,   dataGrid.DataMember];  
  DataRow   dr   =   ((DataRowView)cm.Current).Row;  
   
  DataView   dv=new   DataView(dataset.table1);    
  datagrid.DataSource=dv;    
  以上代码不能在datagrid.MouseDown事件中。只有在之前就将datagrid绑定到dataview才行。否则,每次得到的DataGrid1.CurrentRowIndex都是0  
posted @ 2008-01-08 08:43  Xsi64  阅读(362)  评论(0编辑  收藏  举报