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

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

Related

Type mismatch user form

I'm getting a error mesage when I run this code.
Dim usf as object
If usfOKNAR01.Visible = True Then
k = 1
Set usf = VBA.UserForms(usfOKNAR01) 'here I'm getting the error
ElseIf usfOKNAR02.Visible = True Then
k = 2
Set usf = VBA.UserForms(usfOKNAR02) 'here I'm getting the error mesage
End If
I want to create a dynamic object control which is reffering to 2 Userforms called usfOKNAR01 and usfOKNAR02.
Depending which is visible the proper will be set and then used like this usf.Controls("txt" & k & "oknar13").Value in other part of my code.
I don't know where the issue can be?
Thank you for your help!
I have removed a part of my code and it seems to work but I don't know if this is the proper way to solve my issue.
Here the new code:
Dim usf as object
If usfOKNAR01.Visible = True Then
k = 1 Set
usf = usfOKNAR01
ElseIf usfOKNAR02.Visible = True Then
k = 2 Set
usf = usfOKNAR02
End If
You can't use the name or the class name as an index to VBA.UserForms - it only accepts Integer index arguments. If you don't know the integer index of the collection, you'll have to iterate over it:
Dim usf As Object
Dim found As Boolean
If usfOKNAR01.Visible = True Then
k = 1
Dim candidate As Object
For Each candidate In VBA.UserForms
If TypeOf candidate Is usfOKNAR01 Then
found = True
Exit For
End If
Next usf
If found Then Set usf = candidate
'...
Since you need to do this at least twice, I'd recommend extracting it to a function.
Note that if either of the forms is not loaded when your code runs, VBA will instantiate them when you test whether they are Visible.

error NullReferenceException was unhandled at progressbar

Public Sub GetStationDataFromDatabase()
Dim StationTable As New DataTable
StationTable.TableName = "Station"
Dim Counter As Integer
Dim SqlString As String
Dim OperStaRow As DataRow
Counter = 0
ProgressBar.Visible = True
ProgressBar.Minimum = 1
ProgressBar.Maximum = LocalDataSet.Tables("OR").Rows.Count
ProgressBar.Value = 1
ProgressBar.Step = 1
For Each OperStaRow In LocalDataSet.Tables("OR").Rows
SqlString = "JUST SOME STRING HERE"
ExecuteSqlCommand(SqlString, StationTable)
ProgressBar.PerformStep()
ProgressBar.Refresh()
Counter = Counter + 1
If Counter Mod 20 = 0 Then
Application.DoEvents()
End If
Next
End Sub
so, the error first happpen at progressbar.visible = True. even when i remove it, the error occur the to the line below it. can you tell me what is wrong?
and it happen when user select listbox menu. suppose i have options A and B.
i suspect that there is a typo with progressbar object name. pls check spellings. there is nothing wrong in your code.
other than that,
i suggest that you check row count > 0 before assigning progressbar maximum value.
regards

cannot get selectedvalue of combobox, returns empty

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

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.