cannot get selectedvalue of combobox, returns empty - vb.net

I'm sure this is really something stupid in my code, but I cannot get the selected value from my combobox for the life of me. Here is my code.
Dim objScales As List(Of My.Scale) = Nothing
Dim ExistingDimScale As Double = 0
Dim ExistingDimScaleIndex As Double = 0
_ScaleForm = New ScaleForm
Try
Me.LoadProperties()
If Me.ConfigUnits <> 0 Then
'Get the right scales per units
If Me.ConfigUnits = 1 Then 'imperial
objScales = Me.GetImperialScales()
Else
objScales = Me.GetMetricScales()
End If
'Load up the combobox values
If objScales IsNot Nothing Then
_ScaleForm.cmbScale.DisplayMember = "Name"
_ScaleForm.cmbScale.ValueMember = "DimScale"
For Each objScale In objScales
_ScaleForm.cmbScale.Items.Add(objScale)
'MsgBox(objScale.Name.ToString)
Next
'Set the selected Index to the current dim scale
Double.TryParse(Autodesk.AutoCAD.ApplicationServices.Application.GetSystemVariable("Dimscale").ToString, ExistingDimScale)
ExistingDimScaleIndex = objScales.FindIndex(Function(Val) Val.DimScale = ExistingDimScale)
If ExistingDimScaleIndex = -1 Then
_ScaleForm.cmbScale.SelectedIndex = 0
Else
Integer.TryParse(ExistingDimScaleIndex.ToString, _ScaleForm.cmbScale.SelectedIndex)
End If
Else
MsgBox("There were no scales set")
End If
Else
Throw New System.Exception("Error Reading Configuration Units")
End If
Catch ex As System.Exception
MsgBox(ex.Message)
'handle it here internally
End Try
_ScaleForm.ShowDialog()
If DialogResult.OK = 1 Then
MsgBox(_ScaleForm.cmbScale.SelectedValue)
End If
The second from the last line MsgBox(_ScaleForm.cmbScale.SelectedValue), this is where I want to use the selected value to do stuff but it keeps popping up empty in the messagebox. I'm tired and unsure of why it's not working.

You are not setting the DataSource property of the ComboBox but inserting every item one by one in the items collection. Try to set the DataSource
_ScaleForm.cmbScale.DataSource = objScales
and you will get the SelectedValue set.
In alternative you could read the SelectedItem property that will return a Scale object if something has been selected and then get the DimScale field from this instance
if DialogResult.OK = _ScaleForm.ShowDialog() Then
if _ScaleForm.cmbScale.SelectedItem IsNot Nothing Then
My.Scale obj = CType(_ScaleForm.cmbScale.SelectedItem, My.Scale)
....
End If
End If

Related

Object reference not set to an instance of an object VB.net Exception

I made a simple for loop in VB.net to check every textbox in my webpage, set empty textbox value to 0 and it looks like this:
Dim i As Integer
For i = 1 To 62 Step 1
Dim value0 As String = "textbox" + i.ToString()
tb0 = PlaceHolder1.FindControl(value0)
If tb0.Text = String.Empty Then
tb0.Text = "0"
End If
Next
When I run this code I get this error:
System.NullReferenceException: Object reference not set to an instance
of an object.
Happens here: If tb0.Text = String.Empty Then
Any ideas?
This is because FindControl will return null if the specified control name does not exist.
You may add extra condition to check if tb0 is null or not.
IF tb0 Is NOT Nothing
If tb0.Text = String.Empty Then
tb0.Text = "0"
End If
END IF

Enabling and Disabling cbomboBox in VB.net with modules

I am trying to enable and disable two combo boxes depending on a selection.
Public Function itemsEnabled(item, item2)
Dim cboCate As String
Dim cboItemM = frmStore.cboItem
Dim cboItemM2 = frmStore.cboItem2
cboCate = frmStore.cboCategory.SelectedItem
cboItemM = frmStore.cboItem
cboItemM2 = frmStore.cboItem2
Try
If cboCate = "Coffee" Then
cboItemM.Enabled = True
cboItemM2.Enabled = False
'if coffee is chosen then colddrink combo box is disabled
ElseIf cboCate = "ColdDrink" Then
cboItemM2.Enabled = True
cboItemM.Enabled = False
'if colddrink is chosen then coffe combo box is disable
End If
Catch ex As Exception
MessageBox.Show(ex.ToString())
End Try
Return cboItemM
End Function'
And when I select an option in the cboCate (category) nothing happens, I tried adding ToString() at the end of line 5 but I get the error:
object reference not set to an instance of an object.

How to only check empty visible Maskedtextboxes in vb.net?

I have about 50 Maskedtextboxes, only few of them are visible. What I need is to only check the visible ones if they are empty.
I used this code to check all Maskedtextboxes:
Dim empty = TabLABOR.Controls.OfType(Of MaskedTextBox)().Where(Function(txt) txt.Text.Length = 0)
If empty.Any Then
MessageBox.Show(String.Format("Please fill all fields",
String.Join(",", empty.Select(Function(txt) txt.Name))))
Else
TabControlBlockD.SelectTab(TabMATERIALS)
End If
End Sub
you should use a for each like the following
dim myfrm as MyCurrentForm()
then
for Each item As System.Windows.Forms.Control In myfrm.Controls
If item.GetType Is GetType(System.Windows.Forms.MaskedTexbox) Then
For Each mboxes As MaskedTexbox In item.Controls
If MaskedTexbox.text = "" AND maskedTextbox.visible = true Then
//Make deltu king of the world
End If
Next
End If
Next
That should work.
edit:

To iterate through the values of combo box control using vb.net

I update my question here .. Am using a combo box with no of phone numbers .I want to get the phone no one by one in a variable. Now am using the below code to get the combobox values. But still now am getting the following error message System.Data.DataRowView. Please help me to fix this error. am new for vb.net.
My partial code is here ..
For i = 0 To ComboBox1.Items.Count
Dim s As String
s = Convert.ToString(ComboBox1.Items(i))
Next i
you are using an index which is zero based.
change this:
For i = 0 To ComboBox1.Items.Count
to this:
For i = 0 To ComboBox1.Items.Count - 1
This also works!
Dim stgTest = "Some Text"
Dim blnItemMatched As Boolean = False
'-- Loop through combobox list to see if the text matches
Dim i As Integer = 0
For i = 0 To Me.Items.Count - 1
If Me.GetItemText(Me.Items(i)) = stgTest Then
blnItemMatched = True
Exit For
End If
Next i
If blnItemMatched = False Then
Dim stgPrompt As String = "You entered '" & stgTypedValue & "', which is not in the list."
MessageBox.Show(stgPrompt, "Incorrect Entry", MessageBoxButtons.OK, MessageBoxIcon.Information)
Me.Text = ""
Me.Focus()
End If
Your problem probably happens here:
s = Convert.ToString(ComboBox1.Items(i))
This doesn't return the value. It returns a string representation of the object at the given index, which in your case apparently is of type System.Data.DataRowView.
You would have to cast ComboBox1.Items(i) to the approbriate type and access its Value. Or, since its a DataRowView, you can access the values throgh the appropriate column names:
Dim row = CType(ComboBox1.Items(i), System.Data.DataRowView)
s = row.Item("column_name")
Nevertheless, first of all you should definitely close and dispose the connection, no matter whether the transaction fails or succeeds. This can be done in a finally block (option 1) or with a using statement (option 2).
Option 1
// ...
con1 = New MySqlConnection(str)
con1.Open()
Try
// ...
Catch ex As Exception
Lblmsg.Text = " Error in data insertion process....." + ex.Message
Finally
con1.Close()
con1.Dispose()
End Try
Option 2
// ...
Using con1 as New MySqlConnection(str)
con1.Open()
Try
// ...
Catch ex As Exception
Lblmsg.Text = " Error in data insertion process....." + ex.Message
Finally
con1.Close()
End Try
End using
Even after long time back you will achieve this with simply by following
For Each item As Object In combx.Items
readercollection.Add(item.ToString)
Next
Please try this
For j As Integer = 0 To CboCompany.Items.Count - 1
Dim obj As DataRowView = CboCompany.Items(j)
Dim xx = obj.Row(0)
If xx = "COMP01" Then
CboCompany.SelectedIndex = j
Exit For
End If
Next
I could not find this answer online in its entirety but pieced it together. In the snippet below cbox is a ComboBox control that has the DisplayMember and ValueMember properties initialized.
Dim itemIE As IEnumerator = cbox.Items.GetEnumerator
itemIE.Reset()
Dim thisItem As DataRowView
While itemIE.MoveNext()
thisItem = CType(itemIE.Current(), DataRowView)
Dim valueMember As Object = thisItem.Row.ItemArray(0)
Dim displayMember As Object = thisItem.Row.ItemArray(1)
' Insert code to process this element of the collection.
End While

Enumeration in vb.net

while executing this below lines i got an error. Error:
Collection was modified; enumeration operation may not execute.
Help me to solve this.
Dim i As IEnumerator
Dim item As DataGridItem
Dim bChk As Boolean = False
i = dgOfferStatus.Items.GetEnumerator
For Each item In dgOfferStatus.Items
i.MoveNext()
item = i.Current
item = CType(i.Current, DataGridItem)
Dim chkItemChecked As New CheckBox
chkItemChecked = CType(item.FindControl("chkItemChecked"), CheckBox)
If chkItemChecked.Checked = True Then
Try
bChk = True
lo_ClsInterviewProcess.JobAppID = item.Cells(1).Text
lo_ClsInterviewProcess.candId = item.Cells(9).Text
Dim str, strSchedule1, strSchedule As String
Dim dspath As DataSet
Dim candidateId As Integer
''Moving the resume to Completed folder
ObjInterviewAssessment = New ClsInterviewAssessment
dspath = ObjInterviewAssessment.GetOffComPath(CInt(lo_ClsInterviewProcess.JobAppID), "GetHoldPath")
If dspath.Tables(0).Rows.Count > 0 Then
If Not IsDBNull(dspath.Tables(0).Rows(0).Item(0)) Then
str = dspath.Tables(0).Rows(0).Item(0)
strSchedule1 = str.Replace("Hold", "Completed")
End If
End If
Dim str1 As String
str1 = Server.MapPath(str).Trim
strSchedule = Server.MapPath(strSchedule1).Trim
Dim file1 As File
If file1.Exists(str1) Then
If file1.Exists(strSchedule) Then
file1.Delete(strSchedule)
End If
file1.Move(str1, strSchedule)
End If
''
intResult = lo_ClsInterviewProcess.UpdateApproveStatus(Session("EmployeeId"), strSchedule1)
BindHoldGrid()
If intResult > 0 Then
Alert.UserMsgBox("btnsearch", "Status Updated")
Else
Alert.UserMsgBox("btnsearch", "Status not Updated")
End If
Catch ex As Exception
ExceptionManager.Publish(ex)
Throw (ex)
End Try
End If
Next
If bChk = False Then
Alert.UserMsgBox("btnsearch", "Please Select any Candidate")
End If
'Catch ex As Exception
' ExceptionManager.Publish(ex)
'End Try
End Sub
Look at this part of your code. I think it's what causes your exception.
Dim i As IEnumerator
...
Dim item As DataGridItem
...
i = dgOfferStatus.Items.GetEnumerator
For Each item In dgOfferStatus.Items
i.MoveNext()
item = i.Current ' <-- here be dragons!? '
...
Next
What you're doing seems a little strange. You iterate through the same collection (dgOfferStatus.Items) twice, once with the For Each loop, and once manually using the i iterator. Then you modify items in your collection with item = i.Current. I believe it's this assignment that causes the exception.
(I also don't understand why you would do this. This assignment seems to be completeley superfluous, since i.Current and item should be identical since both iterators are at the same position in the collection.)
The exception basically tries to tell you that you may not modify a collection while you are iterating through it. But you seem to be doing exactly that.