1

我正在创建一个里面Form有一个。Bound DatagridviewForm_LoadRow_Validating上,我将新行添加到Datagridview

Private Sub PurchaseInRowAdd()
        'add new row to datagridview
        Dim dtRow As DataRow = CType(Me.dgvPurchaseIn.DataSource, DataTable).NewRow()
        dtRow.Item("InvoiceID") = 0
        dtRow.Item("KindID") = CType(CType(Me.dgvPurchaseIn.Columns("colPurchaseKind"), DataGridViewComboBoxColumn).DataSource, DataTable).Rows(0)("KindID")
        dtRow.Item("InvoiceSign") = ""
        dtRow.Item("InvoiceNo") = ""
        dtRow.Item("InvoiceDate") = New Date(objController.ProcessYear, objController.ProcessMonth, 1)
        dtRow.Item("ID") = CType(CType(Me.dgvPurchaseIn.Columns("colPurchaseCustomer"), DataGridViewComboBoxColumn).DataSource, DataTable).Rows(0)("ID")
        dtRow.Item("Product") = ""
        dtRow.Item("Price") = "0.00"
        dtRow.Item("Note") = ""
        dtRow.Item("Tax") = CType(CType(Me.dgvPurchaseIn.Columns("colPurchaseKind"), DataGridViewComboBoxColumn).DataSource, DataTable).Rows(0)("Tax")
        dtRow.Item("TaxCode") = CType(CType(Me.dgvPurchaseIn.Columns("colPurchaseCustomer"), DataGridViewComboBoxColumn).DataSource, DataTable).Rows(0)("TaxCode")
        dtRow.Item("VAT") = ""

        CType(Me.dgvPurchaseIn.DataSource, DataTable).Rows.Add(dtRow)
    End Sub

这里的问题是,当用户在该新行中完成输入并按 Enter 时,Row_Validating并没有被触发,因为它下面没有行。Row_Validating那么当用户完成输入并按回车时,如何强制触发?

我找到了这个解决方案,但它不适合我的情况,因为我不想设置Enable AddingTrue. 我想改为通过代码处理行添加。

4

1 回答 1

0

我找到了解决方案,我像这样子类化DataGridView和覆盖ProcessDialogKey

protected override bool ProcessDialogKey(Keys keyData)
        {
            if(keyData == Keys.Enter)
            {
                KeyEnterPress(this, new EventArgs());
            }
            return base.ProcessDialogKey(keyData);
        }

(我用 C# 编写了这个子类)

然后像这样在我的表单中处理按键输入

Private Sub PurchaseInCellKeyDown(ByVal sender As Object, ByVal e As EventArgs)
        If Me.dgvPurchaseIn.CurrentRow.Index = Me.dgvPurchaseIn.Rows.Count - 1 Then
            If PurchaseInRowValidate(Me.dgvPurchaseIn.CurrentRow.Index, True) Then
                Me.PurchaseInRowAdd()
                Me.deselectPurchaseCell(Me.dgvPurchaseIn.CurrentRow.Index)
                Me.dgvPurchaseIn.Rows(Me.dgvPurchaseIn.Rows.Count - 1).Cells("colPurchaseSign").Selected = True
            End If
        End If
    End Sub

这一行:

Me.dgvPurchaseIn.Rows(Me.dgvPurchaseIn.Rows.Count - 1).Cells("colPurchaseSign").Selected = True

将触发行验证

于 2013-07-12T02:55:44.647 回答