To iterate through the values of combo box control using vb.net - 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

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

¿How to get the exact address of a cell? (VB.NET/INTEROP.EXCEL)

Yes. I am using a library that almost nobody likes (COM / Interop). I am practicing doing a program that analize an Excel workbook, identify its columns and the user dials the type of each. Everything serves perfect, I can detect errors in the type of each column (for example if there is a string in a numeric column) but the only type that I am'm having problems is with dates. I asked a question here yesterday regarding dates (because I thought something) but I know from that question that dates are just numbers .... This is no problem because I can use Date.fromOADate.
Well, the situation I face is that if an Excel column contains information of dates and for example, you add a data string in that column of dates, when loading the Excel book in the program, that data string did not mark it as an error .. . but treats it as an empty cell (Thing that has surprised me).
this is the function that I wrote to mark the errors of each column
Protected Friend Function obtenerErroresColumna(ByVal column As String, ByVal page As String, ByVal tipe As String) As Integer
If (Not String.IsNullOrEmpty(column)) Then
Dim cmd As String = "Select [" & column & "] from [" & page & "$]"
Dim errors As Integer = 0
Dim table As New DataTable
Try
Dim adapter As New OleDbDataAdapter(cmd, conexion)
adapter.Fill(table)
adapter.Dispose()
For Each itm In table.Rows
If (tipe.Equals("String")) Then
If (Not IsDBNull(itm(0))) Then
If (IsNumeric(itm(0))) Then
errors += 1
setValueError = itm(0)
End If
End If
ElseIf (tipe.Equals("Numeric")) Then
If (Not IsDBNull(itm(0))) Then
If (Not IsNumeric(itm(0))) Then
errors += 1
setValueError = itm(0)
End If
End If
ElseIf (tipe.Equals("Date")) Then
If (Not IsDBNull(itm(0))) Then
If (Not IsDate(itm(0))) Then
errors += 1
setValueError = itm(0)
End If
End If
End If
Next
table.Dispose()
Return errors
Catch ex As Exception
boxMessage("Error", ex.Message, My.Resources._error).ShowDialog()
Return errors
End Try
Else
Return 0
End If
End Function
Ok, as I said the first two types is running good, the problem is when I start to compare date data type. I have this idea if the column is date type: If the program returns an empty cell (as I said earlier, the string data returns me as empty cells) then the program obtains the address of the cell to make a replacement. I have already written the method for substitution ... only as parameters would have to pass is today's date, the exact address of the cell and the column name.
I would like to check the adress of the current cell of the loop when the variable "itm" is Null (A4, B3, C50.... Etc)
I don't see any reference to Excel.Interop in your code. For the first 26 columns you can use Chr :
Dim adr = Function(col%, row%) Chr(64 + col) & row
Dim B3 = adr(2, 3) ' "B3"
Ok guys, I found the solution of this problem. I didnt use interop but I get what I wanted.
First I needed to get the letter according to the column name. I found the web a function that returns the column letters of excel by passing as a parameter one number
Private Function ColumnIndexToColumnLetter(colIndex As Integer) As String
Dim div As Integer = colIndex
Dim colLetter As String = String.Empty
Dim modnum As Integer = 0
While div > 0
modnum = (div - 1) Mod 26
colLetter = Chr(65 + modnum) & colLetter
div = CInt((div - modnum) \ 26)
End While
Return colLetter
End Function
I insert a counter in the function that detects errors, this counter would count the cells in the column while to get the column number, I create another function that carried the columns in a arrayList.
I take the indexOf function
Protected Friend Function obtenerErroresColumna(ByVal columna As String, ByVal hoja As String, ByVal tipo As String) As Integer
If (Not String.IsNullOrEmpty(columna)) Then
Dim cmd As String = "Select [" & columna & "] from [" & hoja & "$]"
Dim errores As Integer = 0
Dim tabla As New DataTable
Dim cell As Integer = 2
Dim column As New ArrayList
column = cargarMatrizColumnas(hoja)
Try
Dim adapter As New OleDbDataAdapter(cmd, conexion)
adapter.Fill(tabla)
adapter.Dispose()
For Each itm In tabla.Rows
If (tipo.Equals("Cadena")) Then
If (Not IsDBNull(itm(0))) Then
If (IsNumeric(itm(0))) Then
errores += 1
setValoresError = itm(0)
End If
End If
ElseIf (tipo.Equals("Numerico")) Then
If (Not IsDBNull(itm(0))) Then
If (Not IsNumeric(itm(0))) Then
errores += 1
setValoresError = itm(0)
End If
End If
ElseIf (tipo.Equals("Fecha")) Then
If (Not IsDBNull(itm(0))) Then
If (Not IsDate(itm(0))) Then
errores += 1
setValoresError = itm(0)
End If
Else
MsgBox("Direccion: " & ColumnIndexToColumnLetter(column.IndexOf(columna) + 1) & cell)
End If
cell += 1
End If
Next
tabla.Dispose()
Return errores
Catch ex As Exception
cajaMensaje("Error inesperado", ex.Message, My.Resources._error).ShowDialog()
PantallaPrincipal.lbldireccion.ForeColor = Color.Red
Return errores
End Try
Else
Return 0
End If
End Function
Source of the function: https://www.add-in-express.com/creating-addins-blog/2013/11/13/convert-excel-column-number-to-name/

Setting ComboBox Selected Value to AD Query

I'm running an AD query to pull selected attributes from a users profile. I'm selecting extensionAttribute3, 4, 5, 6, 7 & 8. Although I can get the result to display as text, I'd like to set the selected vlaue of a combobox to the results.
So extension attribute 3, 5 & 7 = security questions, 4, 6 & 8 are the answers. I have 3 comboboxes, each with a list of 15 possible security questions users can select from, and then provide answers to. I've got my script to update AD with the questions & answers selected. However when I run the application again, I'd like to pull the existing questions from extensionAttribute 3, 5 & 7, as set as the default selected foreach combobox.
Current AD Query Code:
Private Function GetUserProperties()
Dim ADName As String = GetLogonName()
Dim CurrentPIN As String = Nothing
Dim bSuccess As Boolean = False
Dim dirEntry As DirectoryEntry = GetDirectoryEntry()
Dim dirSearcher As DirectorySearcher = New DirectorySearcher(dirEntry)
Dim Q1Value As String = Nothing
dirSearcher.Filter = ("(samAccountName=" & ADName & ")")
dirSearcher.PropertiesToLoad.Add("extensionAttribute3")
dirSearcher.PropertiesToLoad.Add("extensionAttribute4")
dirSearcher.PropertiesToLoad.Add("extensionAttribute5")
dirSearcher.PropertiesToLoad.Add("extensionAttribute6")
dirSearcher.PropertiesToLoad.Add("extensionAttribute7")
dirSearcher.PropertiesToLoad.Add("extensionAttribute8")
dirSearcher.SearchScope = SearchScope.Subtree
Try
Dim dirResult As SearchResult = dirSearcher.FindOne()
bSuccess = Not (dirResult Is Nothing)
If dirResult Is Nothing OrElse dirResult.GetDirectoryEntry.Properties("extensionAttribute3").Value Is Nothing Then
Return "<not set>"
Else
Q1Value = dirResult.GetDirectoryEntry.Properties("extensionAttribute3").Value.ToString
Q1ComboBox.SelectedIndex = Q1Value
End If
Catch ex As Exception
bSuccess = False
MsgBox("No Connection to the domain." & Environment.NewLine & "Please connect to corporate network & try again.", MsgBoxStyle.Critical, "Network Error")
Application.Exit()
End Try
Return False
End Function
It's really hard to format code in comments, i put them here instead.
I'm not VB programmer, may have syntax error.
You don't provide code for extensionAttribute4-8, so it's hard to find what's wrong with them. Do you mean for extensionAttribute4-8, just repeating the if-else block inside the try-catch does not work?
For example, you cannot get value of extensionAttribute4 below?
' code for extensionAttribute3, omitted here
....
' code for extensionAttribute4
If dirResult Is Nothing OrElse dirResult.GetDirectoryEntry.Properties("extensionAttribute4").Value Is Nothing Then
Return "<not set>"
Else
A1Value = dirResult.GetDirectoryEntry.Properties("extensionAttribute4").Value.ToString
A1ComboBox.SelectedIndex = A1Value
End If
' repeat for extensionAttribute5-8
....
For using the attribute already loaded in SearchResult, you already handle the conversion to string problem (mentioned in comment) by calling ToString. You can just do the same thing. But instead of checking dirResult.GetDirectoryEntry.Properties("...").Value Is Nothing, you should check dirResult.Properties("...").Count > 0.
Dim dirResult As SearchResult = dirSearcher.FindOne()
bSuccess = Not (dirResult Is Nothing)
If dirResult Is Nothing OrElse dirResult.Properties("extensionAttribute3").Count <= 0 Then
Return "<not set>"
Else
Q1Value = dirResult.Properties("extensionAttribute3")[0].ToString
Q1ComboBox.SelectedIndex = Q1Value
End If

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

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.