首页 > 解决方案 > Add a navigation button for a DataGridView

问题描述

I´m writing a code for a simple CRM system containing a Form with a DataGridView and some text fields. The code is written in VB.net.

The DataGridView is linked to a BindingSource, the text fields are connected to the DataGridView and populated by selecting a DataGridViewRow and that works fine.

Code:

Form1.CRM01Form2MainID.Text = Form1.DataGridView1.Rows(Form1.DataGridView1.CurrentRow.Index).Cells(1).Value

I'd like to add navigation buttons (to navigate rows up and down) and for specific reasons I don't want to use a BindingNavigator.

I use the following code to select the next row:

rowidScroll = DataGridView1.CurrentRow.Index (dim is public)
DataGridView1.Rows(rowidScroll + 1).Selected = True

The issue is that the selected row will indeed move one position down but the DataGridView1.CurrentRow.Index isn't updated by 1. As a result the navigation stops after one step and the text fields aren't updated.

It would be appreciated if someone can explain how to fix this problem.

标签: vb.netdatagridviewbindingsource

解决方案


您根本不应该在代码中使用网格。你应该做的正是它BindingNavigator所做的,即使用BindingSource. BindingNavigator只是 的 UI ,特别BindingSourceMoveFirstMovePreviousPositionCount和成员。如果您想创建自己的 UI,那么您可以为相同的成员创建,或者至少为您想要公开的成员创建。例如,如果您只想按记录向前和向后移动,那么您只需要调用and方法:MoveNextMoveLastMovePreviousMoveNext

Private Sub movePreviousButton_Click(sender As Object, e As EventArgs) Handles movePreviousButton.Click
    myBindingSource.MovePrevious()
End Sub

Private Sub moveNextButton_Click(sender As Object, e As EventArgs) Handles moveNextButton.Click
    myBindingSource.MoveNext()
End Sub

我不是 100% 确定,但我认为如果没有上一个或下一个记录可以移动,这些方法将根本无济于事,但你应该测试一下。Button无论哪种方式,如果它不能做任何有用的事情,禁用它可能是一个好主意:

Private Sub movePreviousButton_Click(sender As Object, e As EventArgs) Handles movePreviousButton.Click
    myBindingSource.MovePrevious()
    SetNavigationButtonStates()
End Sub

Private Sub moveNextButton_Click(sender As Object, e As EventArgs) Handles moveNextButton.Click
    myBindingSource.MoveNext()
    SetNavigationButtonStates()
End Sub

Private Sub SetNavigationButtonStates()
    movePreviousButton.Enabled = (myBindingSource.Position > 0)
    moveNextButton.Enabled = (myBindingSource.Position < myBindingSource.Count - 1)
End Sub

您也不应该在网格和其他控件之间手动移动数据。您也应该绑定到这些控件,例如

myBindingSource.DataSource = myDataTable
myDataGridView.DataSource = myBindingSource
myTextBox.DataBindings.Add("Text", myBindingSource, "SomeColumn")

然后,您TextBox将自动显示SomeColumn当前行的值。通过 完成的任何编辑TextBox也将自动推送到数据源。


推荐阅读