I learn visual basic, but I am confused when add value and text in combo box.
This is my sample data:
Kode(value) | Name (Text)
DTR001 | Director
SVS005 | Supervisor
MKR001 | Marketing
In HTML code like this:
<select name="mydata">
<option value="DTR001">Director</option>
<option value="SVS005">Supervisor</option>
<option value="MKR001">Marketing </option>
</select>
How to save add value in combo box VB 6, this is my shortcode:
Private Sub Form_Load()
cmb1.AddItem "test1"
cmb1.AddItem "test2"
cmb1.AddItem "test3"
End Sub
Private Sub cmb_jabatan_Click()
End Sub
You need to maintain an array of the value strings, you can access the correct element by looking at the zero based list index of the combobox item.
Private mValues() As String
Private Sub Form_Load()
ReDim mValues(2)
mValues(0) = "DTR001" '// ListIndex 0
mValues(1) = "SVS005"
mValues(2) = "MKR001"
cmb1.AddItem "Director"
cmb1.AddItem "Supervisor"
cmb1.AddItem "Marketing"
End Sub
Private Sub cmb1_Click()
MsgBox cmb1.List(cmb1.ListIndex) & "/" & mValues(cmb1.ListIndex)
End Sub
You can only directly associate an arbitrary integer with a combobox item using ItemData
.AddItem "Foo"
.ItemData(.NewIndex) = 42
And retrieve with
cmb1.ItemData(listIndex)
You could use this instead of .ListIndex to link to the array if needed.
Related
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
currently my code prompts the user to enter a comma separated list of titles. However, is there a way i can change the code so instead the user can search for the title desired from a drop down menu, click a checkbox by the title, and able to keep searching for required titles until done. And store these strings in an array.
Dim arWords() As String
myt = InputBox("Enter User Input")
arWords() = Split(myt, ",")
For X = 0 To UBound(arWords)
myf = myf & arWords(X) & vbNewLine
Next X
I have an array (arrH) later in the code that has all the titles stored so i think id have to use this as the source, if i need one?. Or so i believe. Im still learning.
arrH = Split(arrTxt(HeaderRow), vbTab)
Thanks!
Create a UserForm.
"the user can search for the title desired from a drop down menu, click a checkbox by the title, and able to keep searching for required titles until done".
UserForm with a ComboBox & CheckBox. On CheckBox_Change event, have the script store the value of ComboBox to a public module-level array and iterate the array index.
Have a "Done" button that hides the userform.
Here's what the Userform code module looks like:
Public SelectedTitles As Variant, ArrCount As Long, EnableEvents As Boolean
Private Sub CheckBox1_Change()
'User has indicated they want to add the currently selected item to the list
If Not EnableEvents Then Exit Sub
If ArrCount = 0 Then 'First item, create the array
SelectedTitles = Array("")
Else
ReDim Preserve SelectedTitles(UBound(SelectedTitles) + 1) 'Next items, add one more space in the array
End If
'Add the selected title to the array
SelectedTitles(ArrCount) = ComboBox1.Value
'Increment the counter
ArrCount = ArrCount + 1
'Reset the checkbox and the combobox
EnableEvents = False
CheckBox1.Value = False
ComboBox1.Value = ""
EnableEvents = True
End Sub
Private Sub CommandButton1_Click()
'Done Button
Me.Hide
End Sub
Private Sub UserForm_Initialize()
EnableEvents = True
End Sub
Here is a sub to aid in adding items to a ComboBox list:
Sub ComboBox_AddFromArray(ByRef ComboBox As Object, ListArray As Variant)
ComboBox.Clear
If IsArray(ListArray) Then
Dim i As Long
For i = LBound(ListArray) To UBound(ListArray)
ComboBox.AddItem ListArray(i), ComboBox.ListCount
Next i
Else
ComboBox.AddItem ListArray, 0
End If
End Sub
This function would go after Load UserForm1 and before UserForm1.Show. And you would input the arguments like ComboBox_AddFromArray UserForm1.ComboBox1, arrH.
The way you'd put this all together is by having a controlling function that does all of the Userform processes and then returns what you need, which is that user selected array of titles.
This is what that would look like
Function UserInputForm(ByRef ArrayOfAllTitles As Variant) As Variant
Load UserForm1
ComboBox_AddFromArray UserForm1.ComboBox1, ArrayOfAllTitles
UserForm1.Show
UserInputForm = UserForm1.SelectedTitles
Unload UserForm1
End Function
And Finally, an example of how to include that function into your main sub:
Dim SelectedTitles As Variant
SelectedTitles = UserInputForm(arrH)
'SelectedTitles is now an array of Variant/String values
Dim i As Long
For i = LBound(SelectedTitles) To UBound(SelectedTitles)
Debug.Print SelectedTitles(i)
'Access individual members of the array using SelectedTitles(i)
Next i
l have a data source that contains two columns
block_name total_lands
A-0 5
A-1 15
A-2 18
A-3 18
And I have two combo boxes one for the block name and the other for the no of lands
the first one is loaded with the block names
Private Sub LoadItems()
SQL.ExecQuery("SELECT block_name FROM blocks;")
For Each i As DataRow In SQL.DBDTable.Rows
ComboBox1.Items.Add(i("block_name"))
Next
End Sub
I want the second one to be loaded with numbers from 1 to whatever is in the data source row total_lands
For example if the user chose the block name as A-1 I want the second combo box to have the items from 1 to 15 add in it
My code trying to do so
Private Sub LoadNoOfLands()
SQL.AddParam("#blockname", ComboBox1.Text)
SQL.ExecQuery("SELECT totla_lands FROM blocks WHERE total_lands LIKE #blockname;")
For Each no As DataRow In SQL.DBDTable.Rows
Dim lands As Integer = no("block_lands")
'For Each i As Integer In lands
'
'
'Next
Next
End Sub
Load required data at once and use Enumerator.Range to generate collection of numbers for second combobox
Public Class Block
Public ReadOnly Property Name As String
Public ReadOnly Property TotalLands As Integer
Public ReadOnly Property Lands As Integer()
Public Sub New(name As String, totalLands As Intger)
Name = name
TotalLands = totalLands
Lands = Enumerable.Range(1, totalLands).ToArray()
End Sub
End Class
Private Function LoadBlocks() As Block()
Dim query = "SELECT block_name, total_lands FROM table"
Dim rows = SQL.ExecuteQuery(query)
Return rows.AsEnumerable().
Select(Function(row) New Block(row.Field(Of String)("block_name"), row.Field(Of Integer)("total_lands"))).
ToArray()
End Function
Private Sub SetupComboBox()
cmbBlocks.DisplayMemeber = "Name"
cmbBlocks.DataSource = LoadBlocks()
End Sub
Private Sub cmbBlocks_SelectionChangeCommitted(sender As Object, e As EventArgs) Handles cmbBlocks.SelectionChangeCommitted
Dim combobox As ComboBox = DirectCast(sender, ComboBox)
Dim block As Block = DirectCast(combobox.SelectedValue, Block)
cmbLands.DataSource = block.Lands
End
I have come up with a simple answer
Private Sub LoadNoOfLands()
cmbLands.Items.Clear()
SQL.AddParam("#blockname", cmbBlocks.Text)
SQL.ExecQuery("SELECT total_lands FROM blocks WHERE block_name LIKE #blockname;")
If SQL.HasException(True) Then Exit Sub
For Each i As DataRow In SQL.DBDTable.Rows
Dim lands = i("total_lands")
Dim r = 1
For r = 1 To lands
cmbLands.Items.Add(r).ToString()
Next
Next
End Sub
This function just adds number to combobox form 1 to the total_lands value
I created a class for the data.
Public Class Block
Public Property Name As String
Public Property TotalLands As Integer
Public Sub New(BlockName As String, Lands As Integer)
Name = BlockName
TotalLands = Lands
End Sub
Public Overrides Function ToString() As String
Return Name
End Function
End Class
The combo box will call .ToString on the items to determine what to display.
We get the data from the database and add it to the List(Of Block)
Public Function FillBlocksList() As List(Of Block)
Dim lst As New List(Of Block)
Using cn As New SqlConnection("Your connection string"),
cmd As New SqlCommand("Select block_name, total_lands From BlockTable;", cn)
cn.Open()
Using reader = cmd.ExecuteReader
Do While reader.Read
Dim b As New Block(reader.GetString(0), reader.GetInt32(1))
lst.Add(b)
Loop
End Using
End Using
Return lst
End Function
To fill the first combo we get the list then loop through it adding the Block objects to the combo. You would probably call this from Form.Load.
Public Sub FillBlocksCombo()
Dim lst = FillBlocksList()
For Each item In lst
ComboBox1.Items.Add(item)
Next
End Sub
To fill the second combo cast the select item back its underlying type, Block and use the TotalLands property to add the numbers.
Private Sub ComboBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ComboBox1.SelectedIndexChanged
Dim NumberOfLands = DirectCast(ComboBox1.SelectedItem, Block).TotalLands
For i = 1 To NumberOfLands
ComboBox2.Items.Add(i.ToString)
Next
End Sub
I have created a table in SQL Server :
its name is [dbo].[Family_Tree]
ID NodeName
1 John
2 George
3 Mike
4 Sandra
5 Jasmine
6 Lucy
I have created a Vb.net Application where I want to present these names in a Combobox or a listbox
Here's the code to fill the Listbox:
Using con As New SqlConnection(My.Settings.ConnString)
Dim DT As New DataTable
Dim Adp As New SqlDataAdapter
With Adp
.SelectCommand = New SqlCommand("Select NodeName , ID From Family_tree", conn)
.Fill(DT)
End With
With ListBox1
.DataSource = DT
.DisplayMember = "NodeName"
.ValueMember = "ID"
End With
End Using
Names are Displayed and nothing is wrong with them , what I want is when I choose any name the listbox returns its corresponding ID .ValueMember = "ID"
, I tested it in a msgbox MsgBox(ListBox1.ValueMember) it always Returns ID , so how can I make it understand that this is a Column not a String ?
thanks in advance...
To get the Value of the current displayed item in the listbox you write
if ListBox1.SelectedValue IsNot Nothing Then
Dim v = Convert.ToInt32(ListBox1.SelectedValue)
.......
ListControl.SelectedValue
Gets or sets the value of the member property specified by the
ValueMember property.
You could use ListBox.SelectedItem, f.e. in it's SelectedIndexChanged event:
Private Sub ListBox1_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles ListBox1.SelectedIndexChanged
Dim curItem As DataRowView = TryCast(ListBox1.SelectedItem, DataRowView)
If curItem IsNot Nothing Then
Dim id = curItem.Row.Field(Of Int32)("ID")
End If
End Sub
I have a requirement that I need to display checkbox on pdf document generated using itextsharp. However, as itextsharp doesn't support html input tag, the checkboxes did not appear on my page. I use asp.net checkboxlist control and I am thinking about adding background image to display the checkbox as checked or not checked, but for some reason, I could not get it to display still. Here is my code:
Protected Sub Checkboxlist1_DataBound(sender As Object, e As EventArgs) Handles Checkboxlist1.DataBound
If test <> "" Then
Dim checklist As List(Of String) = ReturnListofStringClass.ReturnChecklistListOfString(test)
For i = 0 To Checkboxlist1.Items.Count - 1
For Each id As String In checklist
If Checkboxlist1.Items(i).Value = id Then
Checkboxlist1.Items(i).Selected = True
Checkboxlist1.Items(i).Attributes("style") = "background: url(http://renegadeox.com/img/on.png) no-repeat red; height:300px; color: blue; font-size:20px;"
End If
Next
Next
End If
End Sub
The background color applied but not the image. Thanks for your help.
Perhaps this will help.
Protected Sub Checkboxlist1_DataBound(sender As Object, e As EventArgs) Handles Checkboxlist1.DataBound
If test <> "" Then
Dim checklist As List(Of String) = ReturnListofStringClass.ReturnChecklistListOfString(test)
For i = 0 To Checkboxlist1.Items.Count - 1
For Each id As String In checklist
If Checkboxlist1.Items(i).Value = id Then
Dim t AS string= Checkboxlist1.Items(i).Text
Checkboxlist1.Items(i).Text = "<img src='http://renegadeox.com/img/on.png' style='width:10px; height:10px;' alt='' title='' />" & " " & t
End If
Next
Next
End If
End Sub
Cheers