VB6 get a value selected in a combobox - combobox

I'm building a combobox with the following:
Select 1 or 2 seats:
1
2
And I need to show 1 or 2 as selected depending on the result of a query.
How can I do that?
I have done so far:
SQL = " SELECT numberOfSeats FROM mytable "
SQL = SQL & " WHERE userID ='"
SQL = SQL & txtuserID.Text & "'"
Set auxRes = UAN.OpenResultset(SQL, rdOpenDynamic, rdConcurValues, 0)
cmbNumberOfSeats.Clear
cmbNumberOfSeats.AddItem "Select 1 or 2 seats"
cmbNumberOfSeats.AddItem "1"
cmbNumberOfSeats.AddItem "2"
Thanks!!

You can use the ListIndex property of the ComboBox control to get / set the index of the selected item. You use it like so:
Dim nSelectedIndex As Long
nSelectedIndex = cmbNumberOfSeats.ListIndex
If (nSelectedIndex < 0) Then
'No selected item in the combo box
Else
'There's a selected item, handle it
End If
To set the selected item:
cmbNumberOfSeats.ListIndex = nNewSelectedIndex
The index of the first item is 0; when there's no selection, ListIndex returns -1.

Related

MS Access: Combobox controlled records in form don't show up when combobox item is selected by button with vba

I have a form:
where the all textboxes are connected to a source table. The combobox up top, ConcreteItem, controls which record is currently displayed in the form. The combobox works and all the data displays correctly but I also added a Next Item and Previous Item button for the combobox. I have this code for the combobox:
Dim rs As DAO.Recordset
Set rs = Me.RecordsetClone
rs.FindFirst "ItemDescription = '" & Me.cbo_ConcreteItem.Value & "'"
If rs.NoMatch = True Then
MsgBox "No such record"
Else
Me.Bookmark = rs.Bookmark
End If
rs.Close
This works perfectly. But I have this for the Next Item button.
Dim idx As Long
idx = cbo_ConcreteItem.ListIndex
If idx <> cbo_ConcreteItem.ListCount - 1 Then
cbo_ConcreteItem.Value = cbo_ConcreteItem.ItemData(cbo_ConcreteItem.ListIndex + 1)
Else
cbo_ConcreteItem.Value = cbo_ConcreteItem.ItemData(0)
End If
Me.Refresh`
Unfortunately, when the combobox goes on to the next item, the combobox displays the correct selection but nothing changes below it. Even when I have a "refresh line" in the code, nothing changes. The only solution is to actually select from the combobox itself.
Can someone show me what the problem is?
try manually triggering the combo box event when you change the bookmark
add this line after setting the bookmark...
Dim rs As DAO.Recordset
Set rs = Me.RecordsetClone
rs.FindFirst "ItemDescription = '" & Me.cbo_ConcreteItem.Value & "'"
If rs.NoMatch = True Then
MsgBox "No such record"
Else
Me.Bookmark = rs.Bookmark
cbo_ConcreteItem_Change
End If
rs.Close

Storing Listbox Value Generated by a Row Source Query

I am trying to store the value of a listbox (Actual_Polygon_Area) that has been generated via row source query. Each time I run the script my message box tells me that the value of the listbox is null and I suspect it's caused by the row source. The suspected listbox is named Actual_Polygon_Area and the field I am trying to store it in is Polygon_Area within the table FS_Actual_Polygon.
Private Sub Actual_Polygon_Save_Click()
If IsNull(Actual_Polygon_Year) Then
MsgBox "Please enter a year in which this polygon received treatment"
Actual_Polygon_Year.SetFocus
ElseIf IsNull(Actual_Polygon_Season) Then
MsgBox "Please enter the season in which this polygon received treatment"
Actual_Polygon_Season.SetFocus
ElseIf IsNull(Actual_Polygon_Treatment) Then
MsgBox "Please select the treatment type that was completed in this polygon."
Actual_Polygon_Treatment.SetFocus
ElseIf IsNull(Actual_Polygon_Notes) Then
MsgBox "Please write a short summary regarding treatment goals and objectives."
Actual_Polygon_Notes.SetFocus
ElseIf IsNull(Actual_Polygon_Area) Then
MsgBox "Polygon Area is null, please enter a value"
Actual_Polygon_Area.SetFocus
Else
Dim MyConnection As ADODB.Connection
Set MyConnection = CurrentProject.Connection
Dim rsFS_Actual_Polygon As ADODB.Recordset
Set rsFS_Actual_Polygon = New ADODB.Recordset
If IsNull(PolygonNo) Then
'add
rsFS_Actual_Polygon.Open "select * from FS_Actual_Polygon where PolygonNo= " & Actual_Polygon_ID & " and Treatment_Season= '" & Actual_Polygon_Season & "' and Treatment_Type= '" & Actual_Polygon_Treatment & "' and Project_Name = '" & Actual_Polygon_Project_Name & "' and Polygon_Area = " & Actual_Polygon_Area.Value & " and Treatment_Year = " & Actual_Polygon_Year, _
MyConnection, adOpenDynamic, adLockOptimistic
If Not rsFS_Actual_Polygon.EOF Then
MsgBox "The combination of Polygon ID, treatment-year, treatment-season, and treatment type already exist. Please check the combination."
Actual_Polygon_Year.SetFocus
Else
With rsFS_Actual_Polygon
.AddNew
![PolygonID] = Actual_Polygon_ID
![Project_Name] = Actual_Polygon_Project_Name
![Polygon_Area] = Actual_Polygon_Area.Value
![Treatment_Year] = Actual_Polygon_Year
![Treatment_Season] = Actual_Polygon_Season
![Treatment_Type] = Actual_Polygon_Treatment
![Polygon_Notes] = Actual_Polygon_Notes
.Update
End With
Actual_Polygon_Record.Requery
Actual_Polygon_New_Click
End If
I can post the rest of the code if necessary, I just didn't want to post a huge chunk.
You can use the .ItemsSelected and .ItemData methods to find and pass the value of the selected row from the listbox to your table.
This is a fairly typical use of the listbox control, and is a little easier than dealing with a multi-select control, but is still a bit cumbersome. You will need to create a For Each...Next loop to collect the row number of the selected row in your listbox and save to a variable. Then use that variable as the argument of the .ItemData method to return the bound column value for that selected row.
This MSDN article should have everything you need.
EDIT: While the above solution works for multi and single select listboxes, there is a more expedient way for single select listboxes:
Dim i as Integer
i = Me!Actual_Polygon_Area.ListIndex
If i = -1 Then
MsgBox "No item has been selected"
Exit Sub
End If
'Do above prior to `WITH` loop
...'Then in your `WITH` loop:
![Polygon_Area] = Actual_Polygon_Area.ItemData(i)

How to retrieve ID from ComboBox ItemData

I have a table of clients. Each Client has an ID. I'm loading a combobox from SQL Server and only displaying Firstname and LastName. I created this simple select statement.
sql= Select ID, FirstName, LastName
sql =From dbo.tblClients order by LastName
g_rs.open, sql, g_Database
cboNames.AddItem vbNullString
cboNames.ItemData(cboNames.NewIndex) = 0
While Not g_RS.EOF
cboNames.AddItem g_RS("LastName") & ", " & g_RS("FirstName") &
g_RS.MoveNext
Wend
My question is in regards to when I actually choose a name from the combo box. How do i know the ID that's assigned to that client.
You aren't assigning the ItemData in your loop. Your code should look like:
While Not g_RS.EOF
cboNames.AddItem g_RS("LastName") & ", " & g_RS("FirstName")
cboNames.ItemData(cboNames.NewIndex) = g_RS("ID")
g_RS.MoveNext
Wend
Then, in other code you can retrieve the ID from the selected item's ItemData:
Private Sub cboNames_Click()
Dim selectedID as Integer
If cboNames.ListIndex > 0 Then
selectedID = cboNames.ItemData(cboNames.ListIndex)
End If
End Sub

how to filter the combobox values in vb

I am new to VB.I have a policy no. combobox in VB which populates after I enter first four digits of the policy no.However, if I continue to type the number it overwrites what I have already typed and wipes out the dropdown list, as if selecting for the new 4 numbers I typed.I Want to acheive a scenario where I will enter the first 4 numbers to populate the dropdown after that as i go on entering the policyno the values in the dropdown list get searched.
E.G:Policy number: 969003648, as I type 9690 the drop down is filled in with the policy no's starting from 969000001, now as I go on typing the values as 969003 etc the searched values gets limited to the policy no's having 969003 as starting values...Please assist
My code:
Private Sub PolicyNo_KeyDown(KeyCode As Integer, Shift As Integer)
If KeyCode = 46 Or KeyCode = 8 Then
Me.PolicyNo.value = ""
Else
If Len(Me.PolicyNo.Text) >= 4 Then
Me.PolicyNo.RowSource = ""
Call ReloadPolicyNo(Nz(Me.PolicyNo.Text, ""))
Function ReloadPolicyNo(sPolicyNo As String)
Me.PolicyNo.RowSource = "SELECT Inventory.PolicyNo FROM Inventory " & _
"WHERE Left(Inventory.PolicyNo," & Len(Me.PolicyNo.Text) & ") = '" & Me.PolicyNo.Text & "' order by Inventory.PolicyNo"
End Function
Why don't you use the Textchanged event on your combo box to get what is currently in the combobox ?
Example
'THIS FIRES WHEN TEXT IS ENTERED INTO THE COMBOBOX
Private Sub ComboBox1_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles ComboBox1.TextChanged
'GET VALUE IN COMBOBOX
Dim enteredText As String = ComboBox1.Text
Dim strSelect As String = "select * from table where field like = '" & enteredText & "'%"
'load COMBO BOX HERE
End Sub
It's better to use DataView here , I declared DataTable as class Variable.
Dim dt as DataTable
Fetched All the data from database and bind it to declared DataTable, This DataTable further added to DataView and use RowFilter to filter DataView.
Compay_Type is one of the column in my DataTable Below code will filter DataView and bind data where column Company_Type=1
Dim dvComp As New DataView(dt)
dvComp.RowFilter = "Company_Type=1"
ComboBox1.DisplayMember = "CompanyName"
ComboBox1.ValueMember = "CompanyID"
ComboBox1.DataSource = dvComp
To remove Filter just use dvComp.RowFilter = Nothing

Retriving data from ListView control

I have a ListView control set up in details mode with 5 columns. It is populated by code using the following subroutine:
For j = 0 To 14
cmd = New OleDbCommand("SELECT TeacherName, ClassSubject, BookingDate, BookingPeriod FROM " & SchemaTable.Rows(i)!TABLE_NAME.ToString() & " WHERE (((BookingDate)=" & Chr(34) & Date.Today.AddDays(j) & Chr(34) & ") AND ((UserName)=" & Chr(34) & user & Chr(34) & "));", cn)
dr = cmd.ExecuteReader
Dim itm As ListViewItem
Dim itms(4) As String
While dr.Read()
itms(0) = dr(0)
itms(1) = SchemaTable.Rows(i)!TABLE_NAME.ToString()
itms(2) = dr(1)
itms(3) = dr(2)
itms(4) = dr(3)
itm = New ListViewItem(itms)
Manage.ManageList.Items.Add(itm)
End While
Next
Note that this is not the full routine, just the bit that populated the grid.
Now I need to retrieve data from the ListView control in order to delete a booking in my database. I used the following code to retrieve the content of each column:
ManageList.SelectedItems(0).Text
But it only seems to work on index 0. If I do:
ManageList.SelectedItems(3).Text
I get this error:
InvalidArgument=Value of '3' is not
valid for 'index'. Parameter name:
index
I'm pretty much stumped, it seems logical to me that index 1 will point to the 2nd column, index 2 to the 3rd etc, as it's 0 based?
Any help would be appreciated, thanks.
When you say ManageList.SelectedItems(3).Text, you're asking it for the forth item selected in your list, not the forth column of the item selected.
See MSDN
EDIT: Think of it this way: ManageList.SelectedItems(0)=itms, which is a string array. The following example shows how you can access the forth array value of the selected array in the list:
Dim itms() As String = ManageList.SelectedItems(0)
If itms.Length>3 Then
itms(3).DoWhatever
End If
The SelectedItems method returns the selected ListViewItem(s). To access the individual columns within, use the SubItems property.
Note from the documentation:
The first subitem in the
ListViewItem.ListViewSubItemCollection
is always the item that owns the
subitems. When performing operations
on subitems in the collection, be sure
to reference index position 1 instead
of 0 to make changes to the first
subitem.

Resources