我正在更新一些代码以允许Option Strict On。即将出现的一个问题是后期约束。我有一个Form
,其中包含多个不同类型的必需项目(TextBox
,ComboBox
等等。)我有一个功能来检查Form
的有效性,以及然后将焦点设置为第一个没有值的控件。
如果没有Option Strict On,我可以简单地使用基本Object
,并将其设置为缺少值的控件,然后在结尾处调用objMissing.Focus()
,但选项Strict On,编译器不允许后期绑定。
我意识到如果控件都是相同的类型,我可以将丢失的对象转换为TextBox
。有没有办法我仍然可以使用一个变量存储控件来设置焦点?或者我应该立即在每个正在检查值的If
中设置焦点吗?
以下是我正在查看的代码示例(txt_为TextBox
,cbo_为ComboBox
,btn_为Button
类型):
Dim objMissing as Object
If txtItemDescription.Text = String.Empty Then
objMissing = txtItemDescription
strMessage = "You must enter an item description."
ElseIf cboProductType.Text = String.Empty Then
objMissing = cboProductType
strMessage = "You must select a product type."
ElseIf cboComponentType.Text = String.Empty And cboComponentType.Enabled Then
objMissing = cboComponentType
strMessage = "You must select a component type."
ElseIf txtOnHand.Text = String.Empty Then
txtOnHand.Text = "0"
ElseIf txtRented.Text = String.Empty Then
txtRented.Text = "0"
ElseIf txtCost.Text = String.Empty Then
txtCost.Text = "0.00"
ElseIf txtFreight.Text = String.Empty Then
txtFreight.Text = "0.00"
ElseIf Len(txtBarcodePrefix.Text) < 6 Then
objMissing = txtBarcodePrefix
strMessage = "You must enter a 6-digit barcode prefix."
ElseIf cboCondition.Text = String.Empty Then
objMissing = cboCondition
strMessage = "You must enter a condition."
ElseIf btnComponents.Enabled And Me.ComponentList.Count = 0 Then
objMissing = btnComponents
strMessage = "You must select the item components."
ElseIf txtSerialNumber.Text <> String.Empty AndAlso txtOnHand.Text <> String.Empty Then
If CInt(txtOnHand.Text) > 1 Then
objMissing = txtOnHand
strMessage = "You cannot have more than 1 item on hand with the same serial number."
End If
End If
If objMissing IsNot Nothing Then
MessageBox.Show(strMessage)
objMissing.Focus()
End If
答案 0 :(得分:3)
如果将objMissing声明为类型Control,那么您的代码将按您的意愿运行。所有标准的WinForms控件都应该从Control继承。