在数据网格视图中保留组合框单元格

时间:2015-06-08 21:55:00

标签: vb.net datagridview

我有一个包含三列的datagridview。前两个是组合框;第三个是复选框。如果我从组合框的下拉列表中选择一个值,然后通过单击网格外的按钮立即退出datagridview,则不会记住我选择的值。如果我查看该单元格,它包含db.null。如果在退出网格之前单击其他单元格,则单元格值将保留。

我不能指望我的用户记住这样做。围绕这个问题的方法是什么?此外,从我的组合框下拉列表中选择一个值后触发的事件是什么。

我在评论中被要求发布相关代码,所以在这里。感谢alybaba726的回复。

动态构建网格的代码

dgvSchedule.AutoGenerateColumns = False
    Dim hoursCol, timeOfDayCol As New DataGridViewComboBoxColumn
    Dim deleteCol As New DataGridViewCheckBoxColumn

For i As Integer = 1 To 12
    hoursCol.Items.Add(i)
Next
timeOfDayCol.Items.Add("AM")
timeOfDayCol.Items.Add("PM")

hoursCol.DataPropertyName = "Hour"
timeOfDayCol.DataPropertyName = "AM/PM"
deleteCol.DataPropertyName = "Delete"

dgvSchedule.Columns.Add(hoursCol)
dgvSchedule.Columns.Add(timeOfDayCol)
dgvSchedule.Columns.Add(deleteCol)
dgvSchedule.Columns(0).HeaderText = "Hour"
dgvSchedule.Columns(1).HeaderText = "AM/PM"
dgvSchedule.Columns(2).HeaderText = "Delete"
  

将网格绑定到表

的代码
mDataTable = GetTable()


    dgvSchedule.DataSource = mDataTable

Function GetTable() As DataTable
' Create new DataTable instance.
Dim table As New DataTable

' Create four typed columns in the DataTable.
table.Columns.Add("Hour", GetType(Integer))
table.Columns.Add("AM/PM", GetType(String))
table.Columns.Add("Delete", GetType(Boolean))

For i = 1 To mSchedules.Count
    table.Rows.Add(SetAMPMHour(mSchedules(i - 1).ScheduleINetHour), SetAMPM(mSchedules(i - 1).ScheduleINetHour), False)

Next

Return table
End Function
  

读取网格数据的代码

  Dim _Hour As String
            Dim _AMPM As String
            Dim _DeleteIt As Int16

            For Each row As DataGridViewRow In dgvSchedule.Rows

                _Hour = clsUtilities.NullIsBlank(row.Cells(0).Value)
                _AMPM = clsUtilities.NullIsBlank(row.Cells(1).Value)
                If _Hour <> "" Or _AMPM <> "" Then
                    If _Hour = "" Or _AMPM = "" Then
                        MsgBox("Incomplete Row Bypassed " & _Hour & " " & _AMPM)
                    Else
                        _DeleteIt = clsUtilities.NullIsZero(row.Cells(2).Value)
                        If UpdateCaseMixSchedule(GetAbsoluteHour(_Hour, _AMPM), _DeleteIt) = False Then
                            Return False

                        End If
                    End If
                End If

            Next row

1 个答案:

答案 0 :(得分:0)

我在另一个论坛得到了答案,我想分享一下。

Private Sub dgvSchedule_CurrentCellDirtyStateChanged(sender As System.Object, e As System.EventArgs) Handles dgvSchedule.CurrentCellDirtyStateChanged
        If dgvSchedule.IsCurrentCellDirty Then
            dgvSchedule.CommitEdit(DataGridViewDataErrorContexts.Commit)
        End If

    End Sub