Option Strict On, set Focus to unknown object type
I am updating some code to allow Option Strict On. One of the problems that comes up is late binding. I have one Form
with several required elements of different types ( TextBox
, ComboBox
etc.). I have a validation function Form
and then setting focus to the first control that doesn't matter.
Without the Strict On option, I could just create a base one Object
and set it depending on which control is missing and then call it objMissing.Focus()
at the end, but with the Strict On option, the compiler does not allow late binding.
I understand that if the controls were of the same type, I could, for example, pass the missing object to TextBox
. Is there a way I can still do this using a single variable to keep the control to set focus? Or should I just set Focus at once in each of the ones If
that check the value?
Here is the example code I'm looking for (txt_ are TextBox
, cbo_ are ComboBox
, btn_ are Button
types):
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
source to share