我正在创建Form
,其中包含Bound Datagridview
。在Form_Load
或Row_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
触发?
我找到了this解决方案,但它不适合我的情况,因为我不想将Enable Adding
设置为True
。我想通过代码来处理行添加。
答案 0 :(得分: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
将触发行验证