How to check elements from an array in a CheckListBox - vb.net

i have a checklisbox with some value, let's say
"Apple"
"Peach"
"Lemon"
These values came from a dataset.
I have an array with Apple and Lemon: {"Apple", "Lemon"}.
How to check in the checklistbox each value read in this array?
EDIT: In my case, the checklistbox was populate using a dataset provided by a SQL query

In the following code sample, data from SQL-Server (database doesn't matter but this is what I used, what is important is the container the data is loaded into is loaded into a list.
Container to hold data
Public Class Category
Public Property Id() As Integer
Public Property Name() As String
Public Overrides Function ToString() As String
Return Name
End Function
End Class
Class to read data
Imports System.Data.SqlClient
Public Class SqlOperations
Private Shared ConnectionString As String =
"Data Source=.\SQLEXPRESS;Initial Catalog=NorthWind2020;Integrated Security=True"
Public Shared Function Categories() As List(Of Category)
Dim categoriesList = New List(Of Category)
Dim selectStatement = "SELECT CategoryID, CategoryName FROM Categories;"
Using cn As New SqlConnection With {.ConnectionString = ConnectionString}
Using cmd As New SqlCommand With {.Connection = cn}
cmd.CommandText = selectStatement
cn.Open()
Dim reader = cmd.ExecuteReader()
While reader.Read()
categoriesList.Add(New Category() With {.Id = reader.GetInt32(0), .Name = reader.GetString(1)})
End While
End Using
End Using
Return categoriesList
End Function
End Class
Extension method
Which can check or uncheck a value if found in the CheckedListBox and is case insensitive.
Public Module Extensions
<Runtime.CompilerServices.Extension>
Public Function SetCategory(sender As CheckedListBox, text As String, Optional checkedValue As Boolean = True) As Boolean
If String.IsNullOrWhiteSpace(text) Then
Return False
End If
Dim result = CType(sender.DataSource, List(Of Category)).
Select(Function(item, index) New With
{
Key .Column = item,
Key .Index = index
}).FirstOrDefault(Function(this) _
String.Equals(this.Column.Name, text, StringComparison.OrdinalIgnoreCase))
If result IsNot Nothing Then
sender.SetItemChecked(result.Index, checkedValue)
Return True
Else
Return False
End If
End Function
End Module
Form code
Public Class ExampleForm
Private Sub Form2_Load(sender As Object, e As EventArgs) Handles MyBase.Load
CheckedListBox1.DataSource = SqlOperations.Categories
End Sub
Private Sub CheckCategoryButton_Click(sender As Object, e As EventArgs) Handles CheckCategoryButton.Click
CheckedListBox1.SetCategory(CategoryToCheckTextBox.Text, StateCheckBox.Checked)
End Sub
End Class
To check all at once
Private Sub CheckAllButton_Click(sender As Object, e As EventArgs) Handles CheckAllButton.Click
CType(CheckedListBox1.DataSource, List(Of Category)).
ForEach(Sub(cat) CheckedListBox1.SetCategory(cat.Name, True))
End Sub

You haven't mentioned exactly how the CheckedListBox gets populated by the DataSet, I've made the assumption that you add Strings directly to the Items collection.
This code will simply loop through the CheckedListBox and compare the values with the array, whatever the match result, the Checkbox is either ticked or cleared.
Dim theArray() As String = {"Apple", "Lemon"}
For counter As Integer = 0 To CheckedListBox1.Items.Count - 1
Dim currentItem As String = CheckedListBox1.Items(counter).ToString
Dim match As Boolean = theArray.Contains(currentItem.ToString)
CheckedListBox1.SetItemChecked(counter, match)
Next

Use the SetItemChecked method like this:
CheckedListBox1.SetItemChecked(CheckedListBox1.Items.IndexOf("your item goes here"), True)
Note that if the item does not exist, an exception will be thrown, so be sure to check for the item before calling the SetItemChecked() method. To do that, you can check for the return value of IndexOf(). It will be -1 if the item does not exist.

Related

Get a value by index from combobox class

i'm approaching to vbnet from vb6 and i'm triyng to get value from combobox using a class which contains the values i stored in.
here is the class
Private m_ItemText As String
Private m_ItemIndex As Int32
Public Sub New(ByVal strItemText As String, ByVal intItemIndex As Int32)
m_ItemText = strItemText
m_ItemIndex = intItemIndex
End Sub
Public ReadOnly Property ItemIndex() As Int32
Get
Return m_ItemIndex
End Get
End Property
Public ReadOnly Property ItemText() As String
Get
Return m_ItemText
End Get
End Property
I use this method charge the combobox
ComboBox2.Items.Add(New clsComboBoxItem("sometext", 1))
ComboBox2.Items.Add(New clsComboBoxItem("sometext 2", 2))
ComboBox2.Items.Add(New clsComboBoxItem("sometext", 3))
and this on combobox.selectedindexchanged
If ComboBox2.SelectedItem.GetType.ToString = itmCombo.GetType.ToString Then
itmCombo = CType(ComboBox2.SelectedItem, clsComboBoxItem)
MessageBox.Show("Item Text=" & itmCombo.ItemText & " and ItemIndex=" & CStr(itmCombo.ItemIndex))
End If
Can anyone tell help me to understand how get an element by his index stored in the class? Eg writing '2' into a text box, the combo box sould be show "sometext2".
Suppose i want to expand the class adding some values, like m_ItemText2,m_ItemText3 etc, i would learn a method to get all of theese values.
I hope I was clear
Thanks in advance
If you have a DataSource set to a DataTable for your ComboBox, just set the DisplayMember and ValueMember. My test ComboBox is set to DropDownList.
Private Sub FillComboBox()
Dim dt As New DataTable
Using con As New SqlConnection(ConStr),
cmd As New SqlCommand("Select FlavorID,FlavorName From Flavors", con)
con.Open()
Using reader = cmd.ExecuteReader
dt.Load(reader)
End Using
End Using
ComboBox1.DisplayMember = "FlavorName"
ComboBox1.ValueMember = "FlavorID"
ComboBox1.DataSource = dt
End Sub
To display the the values
To display the Text cast to DataRowView (that is the object that is in the Item), provide the field you want and call ToString.
Private Sub ComboBox1_SelectionChangeCommitted(sender As Object, e As EventArgs) Handles ComboBox1.SelectionChangeCommitted
MessageBox.Show(ComboBox1.SelectedValue.ToString)
MessageBox.Show(DirectCast(ComboBox1.SelectedItem, DataRowView)("FlavorName").ToString)
End Sub
If you are adding items one by one, you can still set the DisplayMember and ValueMember.
'https://stackoverflow.com/questions/38206678/set-displaymember-and-valuemember-on-combobox-without-datasource
Private Sub SomeFormsLoadEvent()
ComboBox1.Items.Add(New KeyValuePair(Of String, Integer)("Ultra-fast", 600))
ComboBox1.Items.Add(New KeyValuePair(Of String, Integer)("Fast", 300))
ComboBox1.Items.Add(New KeyValuePair(Of String, Integer)("Medium", 150))
ComboBox1.Items.Add(New KeyValuePair(Of String, Integer)("Slow", 75))
ComboBox1.DisplayMember = "Key"
ComboBox1.ValueMember = "Value"
ComboBox1.DataSource = ComboBox1.Items
End Sub
I found it a bit more complicated to display the text. I had to cast the item to its underlying type (KeyValuePair) then ask for the Key value.
Private Sub ComboBox1_SelectionChangeCommitted(sender As Object, e As EventArgs) Handles ComboBox1.SelectionChangeCommitted
MessageBox.Show(ComboBox1.SelectedValue.ToString)
MessageBox.Show(DirectCast(ComboBox1.SelectedItem, KeyValuePair(Of String, Integer)).Key)
End Sub
As I understand it you want to store values in a class and display and access them through the combobox. How about this approach:
The class for the values:
Public Class clsValues
Private lstItemTexts As New List(Of String)
Public ReadOnly Property AllValues As List(Of String)
Get
Return lstItemTexts
End Get
End Property
'To initialize class with empty list, items can be added with AddItems
Public Sub New()
End Sub
'To initialize class with items, items can still be added with AddItems
Public Sub New(lstItemTexts As List(Of String))
Me.lstItemTexts = lstItemTexts
End Sub
Public Sub AddItem(item As String)
Me.lstItemTexts.Add(item)
End Sub
Public Function GetItemByIndex(index As Integer) As String
Return lstItemTexts(index)
End Function
Public Function GetIndexByItem(item As String) As Integer
Return lstItemTexts.IndexOf(item)
End Function
End Class
You can declare it and fill values like this:
Private Values As New clsValues()
Values.AddItem("Some Text 1")
Values.AddItem("Some Text 2")
or
Private Values As New clsValues(New List(Of String)({"Some Text 1", "Some Text 2"}))
to get a value from combobox
Private Sub ComboBox2_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ComboBox2.SelectedIndexChanged
MessageBox.Show(Values.GetItemByIndex(ComboBox2.SelectedIndex))
End Sub
What #Mary stated is true the ComboBox has values that are useful SEE CODE BELOW
Change gvTxType to be a TextBox to see results when you click on the tvTxType
Private Sub cbTxType_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cbTxType.SelectedIndexChanged
If cbTxType.SelectedIndex > -1 Then
'Dim sindex As Integer
'sindex = cbTxType.SelectedIndex
'Dim sitem As String
sitem = CType(cbTxType.SelectedItem, String)
'MsgBox("You Selected " & sitem)
'Index is ZERO based
gvTxType = sitem
End If
End Sub

Passing list to function as parameter

I have a function that will perform work on a list, but I cannot get it to accept more than one datatype. For example:
Public Sub PopulateListBox (objectList as List(of VariantType), ListboxToPopulate as Listbox)
listboxToPopulate.Items.Clear() 'clears the items in the listbox
For Each item In objectList
listboxToPopulate.Items.Add(item.ToString)
Next
End
The problem is that I have lists of different classes, like employee, building address, etc. I cannot pass a List(Of EmployeeClass) because it says it cannot be converted to List(Of VariantType). I have also tried List(Of Object) and the same result.
I will demonstrate the use by first showing you a sample class.
Public Class Coffee
Public Property ID As Integer
Public Property Name As String
Public Property Type As String
Public Sub New(iid As Integer, sname As String, stype As String)
ID = iid
Name = sname
Type = stype
End Sub
Public Overrides Function ToString() As String
Return Name
End Function
End Class
I added a parameterized constructor just to make it easy to get a fully populate Coffee. You need to add the .ToString override so the list box will know what to display.
Here is where my List(Of Coffee) comes from.
Private Function FillCoffeeList() As List(Of Coffee)
Dim CoffeeList As New List(Of Coffee)
Using cn As New SqlConnection(My.Settings.CoffeeConnection),
cmd As New SqlCommand("Select Top 10 ID, Name, Type From Coffees;", cn)
cn.Open()
Using reader = cmd.ExecuteReader
Do While reader.Read
Dim c As New Coffee(reader.GetInt32(0), reader.GetString(1), reader.GetString(2))
CoffeeList.Add(c)
Loop
End Using
End Using
Return CoffeeList
End Function
As commented by Hans Passant, change the datatype of objectList to IEnumerable(Of Object).
Public Sub PopulateListBox(objectList As IEnumerable(Of Object), ListboxToPopulate As ListBox)
ListboxToPopulate.Items.Clear() 'clears the items in the listbox
For Each item In objectList
ListboxToPopulate.Items.Add(item)
Next
End Sub
Now I can pass a List(Of Coffee) to the PopulateListBox method.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim CList = FillCoffeeList()
PopulateListBox(CList, ListBox1)
End Sub
I can access the properties of the underlying type be casting.
Private Sub ListBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ListBox1.SelectedIndexChanged
Dim t = ListBox1.SelectedItem.GetType
Select Case t.Name
Case "Coffee"
Dim c = DirectCast(ListBox1.SelectedItem, Coffee)
TextBox1.Text = c.ID.ToString
TextBox2.Text = c.Type
End Select
End Sub
You can add additionsl cases depending on what types you are expecting. There is probably a better way to do this.

Populate class from query on VB Net

Help translate C# code from this link Simplest way to populate class from query in C# to VB Net.
Option Infer On
Imports System.Reflection
Private Sub Main()
Dim connectionString = "..."
Dim records = (New Query(connectionString)).SqlQuery(Of TVChannel)("select top 10 * from TVChannel")
End Sub
Private Class TVChannel
Public Property number() As String
Public Property title() As String
Public Property favoriteChannel() As String
Public Property description() As String
Public Property packageid() As String
Public Property format() As String
End Class
Public Class Query
Private ReadOnly _connectionString As String
Public Sub New(ByVal connectionString As String)
_connectionString = connectionString
End Sub
Public Function SqlQuery(Of T)(ByVal query As String) As List(Of T)
Dim result = New List(Of T)()
Using connection = New SqlConnection(_connectionString)
connection.Open()
Using command = connection.CreateCommand()
command.CommandText = query
Using reader = command.ExecuteReader()
Dim columns = Enumerable.Range(0, reader.FieldCount).Select(Function(f) reader.GetName(f)).ToArray()
Dim properties = GetType(T).GetProperties()
Do While reader.Read()
Dim data = New Object(reader.FieldCount - 1){}
reader.GetValues(data)
Dim instance = DirectCast(Activator.CreateInstance(GetType(T)), T)
For i = 0 To data.Length - 1
If data(i) Is DBNull.Value Then
data(i) = Nothing
End If
Dim [property] = properties.SingleOrDefault(Function(x) x.Name.Equals(columns(i), StringComparison.InvariantCultureIgnoreCase))
If [property] IsNot Nothing Then
[property].SetValue(instance, Convert.ChangeType(data(i), [property].PropertyType))
End If
Next i
result.Add(instance)
Loop
End Using
End Using
End Using
Return result
End Function
End Class
but, I got error on this line
Dim instance = DirectCast(Activator.CreateInstance(GetType(T)), T)
System.MissingMethodException: 'No parameterless constructor defined for this object.'
This is a much better pattern to follow. It addresses at least four issues in the original code (sql injection, Nothing vs null, constructor access, unnecessary allocations):
Public Module SQL
Private ReadOnly _connectionString As String = "..."
Public Iterator Function Query(Of T)(ByVal query As String, translate As Func(IDataRecord, T), ParamArray data() As SqlParameter) As IEnumerable(Of T)
Using connection As New SqlConnection(_connectionString), _
command As New SqlCommand(query, connection)
If data IsNot Nothing Then command.Parameters.AddRange(data)
connection.Open()
Using reader As SqlDataReader = command.ExecuteReader()
While reader.Read()
Yield translate(reader)
End While
reader.Close()
End Using
End Using
End Function
End Module
Call it like this:
Private Sub Main()
Dim records = SQL.Query("select top 10 * from TVChannel",
Function(r)
'Yes, you're doing the mapping manually now for each query.
'But this lets you properly account for things NULL, column name mismatches, computed properties, etc.
Return New TVChannel With {
.number = r["number"],
.title = r["title"],
.favoriteChannel = r["favoriteChannel"],
.description = r["description"],
.packageid = r["packageid"],
.format = r["format"]
}
End Function,
Nothing)
For Each channel As TVChannel In records
Console.WriteLine($"Channel {channel.number}, {channel.title}")
Next
End Sub

How to filter an object list based on an unknown property

I created a user control consisting of a text box and data grid.
(code not included on the sample below).
I need to filter the content of the data grid by a specific column.
The name of the column depends on the name of the object properties.
The object will vary, however each control will be bound to a specific object.
How I am using the control example:
Public Class Form1
Private ObjectList As List(Of Object)
Sub New()
' This call is required by the designer.
InitializeComponent()
' Add any initialization after the InitializeComponent() call.
ObjectList = GenerateRandomData()
AddHandler Me.MyUserControl.SelectionStatusChanged, AddressOf UpdateForm
AddHandler Me.MyUserControl.TextChanged, AddressOf UpdateList
Me.MyUserControl.DataSource = ObjectList
End Sub
Private Sub UpdateList()
Dim FilteredList As IEnumerable(Of Object) = From obj As Item In ObjectList
Where obj.Prop_1.StartsWith(Me.MyUserControl.Text)
Select obj
Me.MyUserControl.DataSource = FilteredList.ToList
End Sub
Private Sub UpdateForm()
If Me.MyUserControl.HasItemLoaded Then
Dim NewItem As Item = CType(Me.MyUserControl.SelectedItem, Item)
TextBox1.Text = NewItem.Prop_1
TextBox2.Text = NewItem.Prop_2
TextBox3.Text = NewItem.Prop_3
Return
End If
TextBox1.Text = ""
TextBox2.Text = ""
TextBox3.Text = ""
End Sub
Private Function GenerateRandomData() As List(Of Object)
Randomize()
Dim lst As New List(Of Object)
For i = 0 To 10000
Dim itm As New Item
Dim value As Integer = CInt(Int((999999 * Rnd()) + 1))
Dim value2 As Integer = CInt(Int((999999 * Rnd()) + 1))
itm.Prop_1 = value
itm.Prop_2 = "abc " & value & value2
itm.Prop_3 = value2 & value & " abc"
lst.Add(itm)
Next
Return lst
End Function
End Class
I would like to handle the work of UpdateList() inside the User control (move the code or equivalent result) but the problem is that the control is unaware of the object type so I cannot directly call Prop_1 or whatever is the name of the property from inside the user control.
So far I am accomplishing this by listening for events outside the user control but I will like to remove as much responsibility from the programmer.
Any ideas are welcome.
The following is designed around its SetList method that is used to set the source list (IEnumerable(Of T)) and the name of the property to filter on in the UpDateList method. It use Reflection to retrieve the desired property.
Public Class UserControl1
Private list As IEnumerable
Private filterPropInfo As Reflection.PropertyInfo
Public Sub SetList(Of T)(list As IEnumerable(Of T), filterPropertyName As String)
filterPropInfo = GetType(T).GetProperty(filterPropertyName, GetType(String))
If filterPropInfo Is Nothing Then
Throw New ArgumentException(String.Format("{0} is not a Public String Property on Type: {1}", filterPropertyName, GetType(T).FullName))
End If
Me.list = list
End Sub
Public Sub UpdateList()
Dim FilteredList As IEnumerable(Of Object) = From obj In list
Where CStr(filterPropInfo.GetValue(obj)).StartsWith(Me.Text)
Select obj
Me.DataGridView1.DataSource = FilteredList.ToList
End Sub
End Class
Example usage by calling the test method.
Public Class Form1
Sub test()
Dim l As New List(Of Item)
l.Add(New Item("fred"))
l.Add(New Item("freddy"))
l.Add(New Item("fredrick"))
l.Add(New Item("joe"))
UserControl11.[Text] = "fred"
UserControl11.SetList(l, "Field1")
UserControl11.UpdateList()
End Sub
End Class
Class Item
Public Property Field1 As String
Public Property Field2 As Int32
Public Sub New(f1 As String)
Me.Field1 = f1
End Sub
End Class

sort results (find method) not working

I am using ArcGIS. I am trying to sort the data manually after its found. I created a property class and loop through a Tlist to scrub unwanted data. However right before it binds to the data grid, I receive a cast error. I assume something is coming back null. Am I missing something??
Public Class temp
Public Sub New()
End Sub
Public Property DisplayFieldName As String
Public Property Feature As ESRI.ArcGIS.Client.Graphic
Public Property FoundFieldName As String
Public Property LayerId As Integer
Public Property LayerName As String
Public Property Value As Object
End Class
Public Class templst
Public Sub New()
Dim findresult = New List(Of temp)
End Sub
Private _findresult = findresult
Public Property findresult() As List(Of temp)
Get
Return _findresult
End Get
Set(ByVal value As List(Of temp))
_findresult = value
End Set
End Property
End Class
Private Sub FindTask_Complete(ByVal sender As Object, ByVal args As FindEventArgs)
Dim newargs As New templst() 'puts Tlist (temp) into property
Dim templistNUMONLY As New List(Of temp) 'Tlist of temp
For Each r In args.FindResults 'class in compiled dll.
If Regex.Match(r.Value.ToString, "[0-9]").Success Then
templistNUMONLY.Add(New temp() With {.LayerId = r.LayerId,
.LayerName = r.LayerName,
.Value = r.Value,
.FoundFieldName = r.FoundFieldName,
.DisplayFieldName = r.DisplayFieldName,
.Feature = r.Feature})
End If
Next
newargs.findresult = templistNUMONLY
Dim sortableView As New PagedCollectionView(newargs.findresult)
FindDetailsDataGrid.ItemsSource = sortableView 'populate lists here
End Sub
BIND TO GRID HERE: (Error here)
Private Sub FindDetails_SelectionChanged(ByVal sender As Object, ByVal e As SelectionChangedEventArgs)
' Highlight the graphic feature associated with the selected row
Dim dataGrid As DataGrid = TryCast(sender, DataGrid)
Dim selectedIndex As Integer = dataGrid.SelectedIndex
If selectedIndex > -1 Then
'''''''''''''''''CAST ERROR HERE:
Dim findResult As FindResult = CType(FindDetailsDataGrid.SelectedItem, FindResult)
You populate FindDetailsDataGrid with objects of type temp, but you try to cast it to type FindResult instead. You should do:
Dim selectedTemp As temp = CType(FindDetailsDataGrid.SelectedItem, temp)
'*Create find result from selected temp object here*