DataGridView与frmBooking交互故障:SetFieldsFromDataGridView函数异常
问题排查与解决方案
1. 先确认跨窗体数据传递的核心逻辑
别死磕SetFieldsFromDataGridView函数,先把数据传递的基础逻辑掰正:
- 在
frmCalendar的btnUpdate_Click事件里,先判断是否有选中行,再把选中行通过构造函数传给frmBooking:Private Sub btnUpdate_Click(sender As Object, e As EventArgs) Handles btnUpdate.Click If DataGridView1.SelectedRows.Count > 0 Then Dim selectedRow As DataGridViewRow = DataGridView1.SelectedRows(0) ' 用带参数的构造函数传数据,别直接用无参实例化 Dim bookingForm As New frmBooking(selectedRow) bookingForm.ShowDialog() ' 关闭后刷新日历窗体的表格 RefreshCalendarData() End If End Sub - 在
frmBooking里新增带参数的构造函数,把选中行存为私有变量,避免跨窗体直接访问控件(控件默认是Private,直接访问大概率出问题):Private _targetRow As DataGridViewRow Public Sub New(targetRow As DataGridViewRow) InitializeComponent() _targetRow = targetRow ' 直接在这里调用填充函数,不用等窗体加载 SetFieldsFromDataGridView() End Sub
2. 修复SetFieldsFromDataGridView函数的填充逻辑
把原来依赖跨窗体控件的代码改成用传递过来的_targetRow,同时处理空值和列名匹配问题:
Private Sub SetFieldsFromDataGridView() ' 注意:这里的列名是DataGridView列的【Name属性】,不是表头显示文字! txtCustomerName.Text = _targetRow.Cells("colCustomerName").Value?.ToString() ' 处理日期字段的空值,避免转换报错 dtpBookingDate.Value = If(_targetRow.Cells("colBookingDate").Value IsNot DBNull.Value, CDate(_targetRow.Cells("colBookingDate").Value), DateTime.Now) txtContact.Text = _targetRow.Cells("colContact").Value?.ToString() cboService.SelectedValue = _targetRow.Cells("colServiceID").Value?.ToString() ' 其他控件同理,所有字段都要判断DBNull,防止空引用异常 End Sub
- 关键提醒:列名必须和DataGridView列的
Name完全一致,比如你给列设的Name是colCustomerName,就不能写数据库里的CustomerName(除非你把DataGridView列的Name设成了数据库列名)。
3. 排查窗体加载事件的干扰
如果frmBooking的Form_Load事件里有重置控件、清空数据的代码,会直接覆盖填充好的内容,要:
- 删掉Form_Load里不必要的控件重置逻辑,或者把填充函数放在Form_Load之后执行(用构造函数调用的方式天然避免这个问题)。
4. 验证数据是否真的传过来了
在frmBooking的构造函数里加个断点,查看_targetRow的Cells值:
- 如果
_targetRow是Nothing,说明frmCalendar里的选中行判断逻辑有问题,检查DataGridView1.SelectedRows.Count是否真的大于0; - 如果Cells里的值是
DBNull.Value,说明数据库对应字段为空,要做好容错处理,别直接ToString。
5. 别用跨窗体直接访问控件的写法
很多人会写frmCalendar.DataGridView1.SelectedRows(0)这种代码,但如果frmCalendar不是单例或者已经被销毁,就会报错,用构造函数/属性传递数据是最稳妥的方式。
内容的提问来源于stack exchange,提问作者Al Audrey Perico
相关产品推荐
相关产品推荐

