我有一个DataGrid,里面有一张小桌子。到目前为止,我在这个网格上有一个双击处理程序,它迭代所有行以找到选定的行:
DataTable table = (DataTable)this.dataGrid.DataSource;
int selectedRow = -1;
for (int i=0; i<table.Rows.Count; i++)
if (this.dataGrid.IsSelected(i))
selectedRow = i;
break;
}
if ( selectedRow != -1 ) {
DataRow row = table.Rows[selectedRow];
// More code ...
}
问题:当用户单击列标题并对表进行排序时,table.Rows
不会返回正确的行。它仍然包含未排序的行。
我怎样才能得到正确的列?
编辑1:我有一个System.Windows.Forms.DataGrid
,而不是DataGridView
。我不知道有什么不同,因为我不太了解.Net。我能简单地用DataGridView替换DataGrid吗?
发布于 2010-06-02 12:06:42
DataGrid (视窗)
尝试下面的DataGrid.GetSelectedDataRows
,其中MyBase
是您的DataGrid
的名称。
Public Function GetSelectedDataRows() As DataRow()
Dim oSelectedRows As New ArrayList
Dim oDataTable As DataTable = DirectCast(MyBase.DataSource, DataTable)
For i As Integer = 0 To oDataTable.Rows.Count - 1
If MyBase.IsSelected(i) Then
oSelectedRows.Add(oDataTable.DefaultView(i).Row)
End If
Next
Return DirectCast(oSelectedRows.ToArray(GetType(DataRow)), DataRow())
End Function
DataGridView
使用SelectedRows
属性。它返回DataGridViewRow
对象的集合。因为您知道要绑定一个DataTable
,所以DataGridViewRow.DataBoundItem
属性将是一个DataRow
。有关示例,请查看上面的对象帮助主题。
参考文献
http://msdn.microsoft.com/en-us/library/system.windows.forms.datagrid.aspx的http://msdn.microsoft.com/en-us/library/ms171628.aspx
摘录
为了向后兼容和满足特殊需要,保留了DataGrid控件。对于几乎所有的目的,您都应该使用DataGridView控件。在DataGridView控件中不可用的DataGrid控件中唯一可用的功能是在单个控件中分层显示来自两个相关表的信息。必须使用两个DataGridView控件才能显示主/详细关系中的两个表的信息。
发布于 2010-06-02 11:56:00
为什么不使用DataGridView.SelectedRows
属性呢?然后对这些行使用DataBoundItem
来访问底层数据。这可能是DataRowView
类型。在这种情况下,请使用DataRowView.Row
属性。
foreach (DataGridViewRow dgvrow in dataGrid.SelectedRows)
{
DataRow row = null;
if (dgvrow.DataBoundItem is DataRowView)
row = (dgvrow.DataBoundItem as DataRowView).Row as DataRow;
else
row = dgvrow.DataBoundItem as DataRow;
// ... stuff
}
https://stackoverflow.com/questions/2957231
复制相似问题