vb.net - 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.
解决方案
您根本不应该在代码中使用网格。你应该做的正是它BindingNavigator
所做的,即使用BindingSource
. BindingNavigator
只是 的 UI ,特别BindingSource
是MoveFirst
、MovePrevious
、Position
、Count
和成员。如果您想创建自己的 UI,那么您可以为相同的成员创建,或者至少为您想要公开的成员创建。例如,如果您只想按记录向前和向后移动,那么您只需要调用and方法:MoveNext
MoveLast
MovePrevious
MoveNext
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
也将自动推送到数据源。
推荐阅读
- python - 如何使用 grequest.post 进行多处理
- postgresql - 如何合并重复行而不删除行
- c# - 如何从文本文件中读取序列号
- django - AttributeError:“NoneType”对象在 openEdx exchange_token api 上没有属性“get”
- laravel - 将 laravel 部署到 Nginx 中出现错误“无法打开流:没有这样的文件或目录”
- reactjs - ScrollView 不跟踪当前位置。轻按时它会重置回之前的位置
- perl - 需要遍历目录 - 删除匹配模式的行
- html - 背景图像不会出现在 HTML 中
- python - 使用 Python 推导出连续时间戳之间的增量
- sql-server - 如何使用 IP 通过 Internet 连接到 SQL Server 以运行 Windows 应用程序?