Dropdown With filtered value after text entered or edited in VB6 - combobox

I need dropdown list with text field where i can type and dropdown will filter on basis of text.
Like I have data of all countries name and I type "AME" in my textbox so only country containing word "AME" it will show list of countries containing character "AME" only and I can select from list (Like America).
I tried using combo box
Private Sub Combo1_GotFocus()
Combo1.AddItem "America"
Combo1.AddItem "Europe"
Combo1.AddItem "China"
Combo1.AddItem "INDIA"
Combo1.AddItem "London"
End Sub
There are 2 issue I am facing
When combo box got focus the dropdown is not opening i have to click on arrow
When I type "LO" I need dropdown to filter list with containing data with text "LO" only
Like I type "ch" it will only show china and can select china only

Generally, I like using third-party controls for features that are not included with standard controls. However, a combination of API calls and the KeyPress event may get you close enough.
For easier coding this solution depends upon a Recordset containing country names.
Option Explicit
Private Declare Function SendMessage Lib "user32" Alias "SendMessageA" _
(ByVal hwnd As Long, _
ByVal wMsg As Long, _
ByVal wParam As Long, _
lParam As Any) As Long
Private Const CB_SHOWDROPDOWN = &H14F
Private m_Countries As ADODB.Recordset
Private Sub Form_Load()
Set m_Countries = New ADODB.Recordset
m_Countries.Fields.Append "Country", adVarChar, 50
m_Countries.Open
m_Countries.AddNew "Country", "America"
m_Countries.AddNew "Country", "Europe"
m_Countries.AddNew "Country", "China"
m_Countries.AddNew "Country", "Chicago"
m_Countries.AddNew "Country", "INDIA"
m_Countries.AddNew "Country", "London"
m_Countries.MoveFirst
Combo1.Text = ""
FillCombo
End Sub
Private Sub Combo1_GotFocus()
SendMessage Combo1.hwnd, CB_SHOWDROPDOWN, True, ByVal 0
End Sub
Private Sub Combo1_LostFocus()
SendMessage Combo1.hwnd, CB_SHOWDROPDOWN, False, ByVal 0
End Sub
Private Sub Combo1_KeyPress(KeyAscii As Integer)
Dim Filter As String
If KeyAscii > 31 Then
Filter = Combo1.Text & Chr(KeyAscii) 'typed char
ElseIf KeyAscii = 8 And Combo1.Text <> "" Then
Filter = Left(Combo1.Text, Len(Combo1.Text) - 1) 'backspace
End If
If Filter <> "" Then
m_Countries.Filter = "Country LIKE '" & Filter & "%'"
Else
m_Countries.Filter = ""
End If
FillCombo
End Sub
Private Sub FillCombo()
Dim i As Integer
'to avoid interferring with the textbox of the combo don't use the Clear method
For i = Combo1.ListCount - 1 To 0 Step -1
Combo1.RemoveItem i
Next
Do While Not (m_Countries.BOF Or m_Countries.EOF)
Combo1.AddItem m_Countries.Fields("Country").Value
m_Countries.MoveNext
Loop
End Sub

Related

How to access several dymanically created Combobox at form load?

I'm creating comboboxes on form load, but the thing is once I have added a new cb I can't access (set value, edit properties, etc) of the prior ones.
See Below Example:
Sub Start_stackoverflow()
Dim strings() As String = {"Green", "Purple", "Red"}
Dim x as integer
For x = LBound(strings) To UBound(strings)
NewDropDown(x,50,100,strings(x),strings(x))
Next x
End Sub
Private Sub NewDropDown(ByVal Number As Integer, ByVal PosX As Integer, ByVal PosY As Integer, ByVal Name As String, ByVal Text As String)
cbComboBox = New ComboBox
cbComboBox.Location = New Point(150, PosY - 4%)
cbComboBox.Name = Number
cbComboBox.ForeColor = Color.White
cbComboBox.BackColor = Color.DarkBlue
cbComboBox.Text = Name
cbComboBox.AutoSize = True
Me.Controls.Add(cbComboBox)
End Sub
So this is what happens, I can create the comboboxes just fine, add the values but if I wanted to edit the combobox Green for example (since it was first) I cant.
Even If I try this:
Sub Test()
UpdateComboBoxCurrentlySelected(Green, MyValueIwantSelected)
End Sub
Sub UpdateComboBoxCurrentlySelected(ByVal SetGrpName As ComboBox, ByVal CurrentItem As String)
SetGrpName.Text = (CurrentItem)
SetGrpName.SelectedText = (CurrentItem)
SetGrpName.SelectedItem = (CurrentItem)
SetGrpName.SelectedIndex = (CurrentItem)
SetGrpName.SelectedValue = (CurrentItem)
End Sub
Can anyone shed some light on this, that way I will know how to do it properly.
Thanks
You either need to hold a reference to the object you want to edit:
' At form level
Private dropdowns As Dictionary(Of String, Combobox) = New Dictionary(Of String, ComboBox)
' Populate from Sub Start_stackoverflow()
Dim dropdown As ComboBox = Nothing
' ...
dropdown = NewDropDown(x,50,100,strings(x),strings(x))
dropdowns.Add(dropdown.Name, dropdown)
' change UpdateComboBoxCurrentlySelected signature to
Sub UpdateComboBoxCurrentlySelected(ByVal SetGrpName As String, ByVal CurrentItem As String)
' get the dropdown by name
Dim dropdown as ComboBox = dropdowns(SetGrpName)
' ...
Or you can iterate over all the controls in the form looking for the one with the name you asked for.
Dim foundControl As ComboBox = Nothing
For Each control As Control In Me.Controls
If control.GetType Is GetType(ComboBox) AndAlso (control.Name = SetGrpName) Then
foundControl = control
End If
Next
If Not Nothing Is foundControl Then
' Do something with your control.
End If

Visual Basic Issue getting listbox to populate from text file

I am stuck and have tried re-writing my code multiple times and cannot figure out a solution. The application has a text file containing items and prices in a sequential access file. The app should display the price corresponding with the item when it is selected from the list box. Each line in the text file contains the item's number followed by a comma and then the price.
I need to define a structure named item. The structure has 2 member variables, a string to store the item number and a decimal storing the price. I also need to declare a class level array with 5 item structure variables. The load even should read the items and prices and store this info in the class-level array. Then it should add the item numbers to the list box.
This is what I have so far but nothing is working.
Option Explicit On
Option Strict On
Option Infer Off
Public Class frmMain
'declare structure with 2 member variables
Structure Item
Public strItemNum As String
Public decPrice As Decimal
End Structure
'declare array for 5 item structure variables
Private items(4) As Item
Private Sub btnExit_Click(sender As Object, e As EventArgs) Handles btnExit.Click
Me.Close()
End Sub
Private Sub frmMain_Load(sender As Object, e As EventArgs) Handles Me.Load
'declare variables
Dim inFile As IO.StreamReader
Dim strLineofText As String
Dim intSub As Integer
'check if the file exists
If IO.File.Exists("ItemInfo.txt") Then
'open the file
inFile = IO.File.OpenText("ItemInfo.txt")
'read the file
Do Until inFile.Peek = -1 OrElse
intSub = items.Length
strLineofText = inFile.ReadLine.Trim
'add item to list box
lstNumbers.Items.Add(items(intSub).strItemNum)
Loop
'close the file
inFile.Close()
Else
MessageBox.Show("Can't find the ItemInfo.txtfile",
"Kensington Industries",
MessageBoxButtons.OK,
MessageBoxIcon.Information)
End If
End Sub
Private Sub lstNumbers_SelectedIndexChanged(sender As Object, e As EventArgs) Handles lstNumbers.SelectedIndexChanged
lblPrice.Text = items(lstNumbers.SelectedIndex).decPrice.ToString("C2")
End Sub
End Class
I think that you need to change the name of Structure. Item can be used in another references.
Try to change the name to itemstr (for example)
Do Until inFile.Peek = -1 OrElse
intSub = items.Length
strLineofText = inFile.ReadLine.Trim
'add item to list box
Dim arr As String() = str.Split(","C)
Dim valitem As New itemstr()
valitem.text = arr(0)
valitem.value = Convert.ToDecimal(arr(1))
lstNumbers.Items.Add(valitem)
Loop
Thanks everyone. I ended up starting over again and trying something different that works finally!
Option Explicit On
Option Strict On
Option Infer Off
Public Class frmMain
'declare structure
Structure Item
Public strItemNum As String
Public decPrice As Decimal
End Structure
'declare class level array
Public itemList(4) As Item
Private Sub btnExit_Click(sender As Object, e As EventArgs) Handles btnExit.Click
Me.Close()
End Sub
Private Sub frmMain_Load(sender As Object, e As EventArgs) Handles Me.Load
'declare variables
Dim inFile As IO.StreamReader
Dim strLineOfText As String
Dim decPrice As Decimal
Dim strInfo(4, 1) As String
'check to see if the file exists
If IO.File.Exists("ItemInfo.txt") Then
'open the file
inFile = IO.File.OpenText("ItemInfo.txt")
For intRow As Integer = 0 To strInfo.GetUpperBound(0)
'read the line
strLineOfText = inFile.ReadLine
'assign substring from comma to first coloumn
strInfo(intRow, 0) = strLineOfText.Substring(0, strLineOfText.IndexOf(","))
Dim intSep As Integer = strLineOfText.IndexOf(",") + 1
'assign substring after comma to 2nd column
strInfo(intRow, 1) = strLineOfText.Substring(intSep)
'assign first column value to strItemNum variable
itemList(intRow).strItemNum = (strInfo(intRow, 0))
Decimal.TryParse(strInfo(intRow, 1), decPrice)
'assign 2nd columnn value to decPrice variable
itemList(intRow).decPrice = decPrice
'add item to listbox
lstNumbers.Items.Add(itemList(intRow).strItemNum)
Next intRow
'clost the file
inFile.Close()
Else
'error message if file cannot be found
MessageBox.Show("Can't find the ItemInfo.txtfile",
"Kensington Industries",
MessageBoxButtons.OK,
MessageBoxIcon.Information)
End If
End Sub
Private Sub lstNumbers_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs) Handles lstNumbers.SelectedIndexChanged
'display the price
lblPrice.Text = itemList(lstNumbers.SelectedIndex).decPrice.ToString("C2")
End Sub
End Class

How to Make Array Items As Separate Links in Link Label

I have a LinkLabel which is set up to receive some URLs that result from making a selection in a ComboBox. What I'm trying to accomplish is for the user to select a state from my combo, and then be able to click the individual links that appear in link label.
Having my links in array, what I'm getting is the array displays the links as "one whole" string, and I want them to separate links. Here's what I have:
Public arrAlabama(2) As String
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
' Create array for Alabama and add items.
arrAlabama(0) = "http://www.rolltide.com/"
arrAlabama(1) = "http://www.crimsontidehoops.com/"
arrAlabama(2) = "http://centralalabamapride.org/"
End Sub
Private Sub cboSelectState_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cboSelectState.SelectedIndexChanged
' Populate the link label.
If cboSelectState.SelectedIndex = 0 Then
lnklblLinkbox.Text = arrAlabama(0) _
& vbNewLine & arrAlabama(1) _
& vbNewLine & arrAlabama(2)
End If
End Sub
I'll have about 3 other arrStateName type arrays, so my SelectedIndex will span from [0] to [3], and each array will contain 3 URL links.
So where am I going wrong here? If anyone can give me a boost in the right direction I would appreciate it. Some suggested using Dictionary data type, but I'm new to and when I tried test it out, I got frustrated because it doesn't seem to produce the results I want. Using the TKey and TValue throws me off, and I can never get all of my links to display in the box. I used Integer for my keys, and String for my values (links), but couldn't make it work. Some much needed guidance would be appreciated. Is what I'm trying to do possible, or should I be using some other control types?
Make a class object:
Public Class StateLinks
Public Property State As String
Public Property Links As New List(Of String)
Public Overrides Function ToString() As String
'tells the combobox what to display
Return State
Public Sub New(state As String)
Me.State = state
End Sub
End Class
Load some statesLinks into a List(OF T):
Private stateLinksList As New List(Of StateLinks)
Private Sub LoadMe() Handles Me.Load
Dim coState As New StateLinks("Colorado")
coState.Links.Add("some link")
stateLinksList.Add(coState)
' continue adding then bind them
cboSelectState.DataSource = stateLinksList
End Sub
Get the links from the selection:
Private cb_selectionChanged() Handles cboSelectState.SelectedIndexChanged
Dim state = TryCast(cb.SelectedItem, StateLinks)
If Not state Is Nothing
For Each link As String In state.Links
'each link now available
Next
End If
Add a RichTextBox and set Detect Urls = true, BorderStyle = None, Backcolor = color of form, if it is on form. The size should be large enough to hold the url's. Then
Private Sub cboSelectState_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cboSelectState.SelectedIndexChanged
'Populate RichTextBox1.
If cboSelectState.SelectedIndex = 0 Then
RichTextBox1.Text = arrAlabama(0) _
& vbNewLine & arrAlabama(1) _
& vbNewLine & arrAlabama(2)
End If
End Sub
In
Private Sub RichTextBox1_LinkClicked(sender As System.Object, e As System.Windows.Forms.LinkClickedEventArgs) Handles RichTextBox1.LinkClicked
Dim txt As String = e.LinkText 'txt is the link you clicked
End Sub
valter

Visual Studio 2010 form creation: fill an array with contents of a combobox

Trying to knock out a project that's hanging my code without re-writing the entire thing. In it, I just need to populate an array with the information already in the Names combobox in order to proceed. As I'm not using .NET, my options are limited.
(The end result)*Add a button named “btnShowBalance” displaying the text “ShowBalance.” Write code in its event handler asking the user to enter a client’s name (InputBox). Search the names array for the name entered. If the name is found, use its location to retrieve the matching balance from the balances array. Display the client’s name and balance if the client exists; otherwise, display a not-found message. ****
Public Class Form1
Dim Balances(7) As Decimal
Dim Names(7) As String
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
cboNames.Items.Add("John One")
cboNames.Items.Add("Jack Two")
cboNames.Items.Add("John Three")
cboNames.Items.Add("Jack Four")
cboNames.Items.Add("John Five")
cboNames.Items.Add("Jack Six")
cboNames.Items.Add("John Seven")
cboNames.Items.Add("Jack Eight")
cboBalances.Items.Add("235.50")
cboBalances.Items.Add("78943.98")
cboBalances.Items.Add("230781.10")
cboBalances.Items.Add("78362.00")
cboBalances.Items.Add("12097.20")
cboBalances.Items.Add("89267.34")
cboBalances.Items.Add("34959.06")
cboBalances.Items.Add("559284.50")
For i = 0 To cboNames.Items.Count - 1
Names(i) = cboNames.Text
Next
For i = 0 To cboBalances.Items.Count - 1
Names(i) = cboBalances.SelectedItem
Next
End Sub
Private Sub btnShowBalance_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnShowBalance.Click
Dim strResult As String
strResult = InputBox("Enter the name of the customer", "Balance Finder")
For i = 0 To Names.Length - 1
If strResult = Names(i) Then
MessageBox.Show(Names(i).ToString & " " & Balances(i).ToString)
End If
Next
End Sub
End Class

Add Array ID's to Label Text and List Box VB.NET

Its been nearly a year since I messed with VB, but I am having an issue on my first assignment of the semester which is supposed to be a refresher. What I am supposed to do is make an application that I input a students name, address, GPA, age by textbox, and which year(freshman, sophomore, other) by radio, and classes by checkbox.
Once filled out I need to take that information and have it previewed in a label.text. If it looks right, I need the textbox.text info concatenated into a listbox. No matter what I try or do it either shows String.Array() in the preview or the program crashes at line 57 any help or insight would be appreciated.
Public Class Form1
'CIS259 Spring 2014 Matthew McQuarrie
'Declare Student Data as a String of 9 arrays
Dim StudentData(8) As String
Private Sub btnExit_Click(sender As Object, e As EventArgs) Handles btnExit.Click
'Close application
Me.Close()
End Sub
Private Sub btnReset_Click(sender As Object, e As EventArgs) Handles btnReset.Click
'Clear entire form
txtName.Clear()
txtAddress.Clear()
txtGPA.Clear()
txtAge.Clear()
radFreshman.Checked = False
radSophomore.Checked = False
radOther.Checked = False
chkCIS.Checked = False
chkMath.Checked = False
chkScience.Checked = False
chkHistory.Checked = False
lblPreview.Text = ""
End Sub
Public Sub btnPreview_Click(sender As Object, e As EventArgs) Handles btnPreview.Click
StudentData(0) = txtName.Text
StudentData(1) = txtAddress.Text
StudentData(2) = txtGPA.Text
StudentData(3) = txtAge.Text
'Find which radio button is checked to add to StudentData
If radFreshman.Checked = True Then
StudentData(4) = "Freshman"
ElseIf radSophomore.Checked = True Then
StudentData(4) = "Sophomore"
ElseIf radOther.Checked = True Then
StudentData(4) = "Other"
End If
'Find which check boxes are checked to add to StudentData
If chkCIS.Checked = True Then
StudentData(5) = "CIS"
If chkMath.Checked = True Then
StudentData(6) = "Math"
If chkScience.Checked = True Then
StudentData(7) = "Science"
If chkHistory.Checked = True Then
StudentData(8) = "History"
End If
End If
End If
End If
'Show StudentData ino the text of lblPreview
lblPreview.Text = StudentData(0 & 1 & 2 & 3 & 4 & 5 & 6 & 7 & 8)
End Sub
Private Sub btnStudent_Click(sender As Object, e As EventArgs) Handles btnStudent.Click
'Add StudentData elements to Student list
lstStudents.Items.Add(StudentData(0 & 1 & 2 & 3))
End Sub
End Class
maybe this approach I used here can help, but there a few differences..
my source is database.. I concatenate the fields in the database (the source)
and I display only the text, not the id on the listbox displaymember. you could concatenate the id to the textfield from the source and displya the fullstring contactenated.
'create the adapter
Dim adapterU As New OleDb.OleDbDataAdapter("Select id,nombre+' '+apellido as fullname from users", con)
'create a datatable
Dim datatableU As New DataTable
'bring the info from the adapter (database) into the datatable.
adapterU.Fill(datatableU)
'relate the datasource (datable) to the listbox lsUsers
lsUsers.DataSource = datatableU
lsUsers.ValueMember = "id"
lsUsers.DisplayMember = "fullname"

Resources