【发布时间】:2016-03-25 03:23:18
【问题描述】:
我正在 vb.net 中开发 windows 应用程序。
我有几个列的数据网格,我想对我选择的列进行排序。
如下图所示,我已经选择了 ID 列,当我点击排序按钮时,它应该得到升序或降序排序。
(现在我不担心顺序,我对代码更感兴趣。)
我检查了几个关于排序问题的问题,但没有人回答其中涉及哪些事件,他们只给出了一个代码。
到目前为止,我只能编写下面的代码来选择列,但这不起作用,因为我在代码中编写了硬编码的 0 列索引。
如何编写选择列和排序的代码?
Private Sub gvBatchList_ColumnHeaderMouseClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellMouseEventArgs) Handles gvBatchList.ColumnHeaderMouseClick
For Each c As DataGridViewColumn In gvBatchList.Columns
c.SortMode = DataGridViewColumnSortMode.NotSortable
c.Selected = False
Next
gvBatchList.SelectionMode = DataGridViewSelectionMode.FullColumnSelect
gvBatchList.Columns(0).Selected = True
End Sub
提示:我使用 Access 数据库来存储记录并使用集合,同时将记录绑定到网格视图。
下面的代码展示了我是如何绑定记录的......
Private Sub LoadAllRegularEmployees()
Try
Me.Cursor = Cursors.WaitCursor
DataGridView1.AutoGenerateColumns = False
Dim oEmployees As New Employees
oEmployees.LoadAllRegularEmployees()
DataGridView1.DataSource = oEmployees
lblEmployeesCount.Text = "Toal Employees (" + oEmployees.Count().ToString + ")"
txtEmployeeSearch.Focus()
Me.Cursor = Cursors.Arrow
Catch ex As Exception
Me.Cursor = Cursors.Arrow
MessageBox.Show("Error :- " + ex.Message.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
End Sub
【问题讨论】:
-
是否将列的
SortMode的属性设置为Automatic不是一个选项?然后用户只需点击列标题即可进行排序。 -
这个问题应该使用
datagridview的标签而不是datagrid。 OP 还应该提供更多信息,至少他正在使用什么样的数据源。