VB.Net : How do you bind a dictionary collection to a Combobox? - vb.net-2010

I am trying to bind this dictionary collection to a combobox but the display
is not correct. The displayMember should be the ProvName and the ValueMember should be the key.
Private Sub Button8_Click(sender As Object, e As EventArgs) Handles Button8.Click
Dim Country1 As Dictionary(Of String, Province)
Country1 = Module1.CreateCountry
'Display results in combox
ComboBox3.DataSource = New BindingSource(Country1, Nothing)
ComboBox2.DisplayMember = "Value"
ComboBox2.ValueMember = "Key"
End Sub
Module Module1
Public provinces As CollectionBase
Function CreateCountry() As Dictionary(Of String, Province)
Dim Country As New Dictionary(Of String, Province)
Dim Prov As Province
Prov = New Province
With Prov
.Abbrv = "Qc"
.ProvName = "Quebec"
.Population = "7 500 000"
.Region = "East"
End With
Country.Add(Prov.Abbrv, Prov)
Prov = New Province
With Prov
.Abbrv = "BC"
.ProvName = "British Columbia"
.Population = "4 500 000"
.Region = "West"
End With
Country.Add(Prov.Abbrv, Prov)
Prov = New Province
With Prov
.Abbrv = "NS"
.ProvName = "Nova Scotia"
.Population = "2 000 000"
.Region = "Maritimes"
End With
Country.Add(Prov.Abbrv, Prov)
Prov = New Province
With Prov
.Abbrv = "AB"
.ProvName = "Alberta"
.Population = "5 500 000"
.Region = "Prairies"
End With
Country.Add(Prov.Abbrv, Prov)
Return Country
End Function
End Module
Public Class Province
Public Property Abbrv As String
Public Property ProvName As String
Public Property Population As String
Public Property Region As String
Public Overrides Function ToString() As String
Return ProvName
End Function
End Class

Here is the sample source code:
'Declare and Fill a generic Dictionary
Dim dictionary As New Dictionary(Of String, Integer)
dictionary.Add("one", 1)
dictionary.Add("two", 2)
dictionary.Add("three", 3)
dictionary.Add("four", 4)
dictionary.Add("five", 5)
dictionary.Add("six", 6)
dictionary.Add("seven", 7)
dictionary.Add("eight", 8)
'Initialize DisplayMember and ValueMember of an existing combobox to be filled with dictionary values
cboCombo.DisplayMember = "Key"
cboCombo.ValueMember = "Value"
'Bind the combobox to dictionary
cboCombo.DataSource = New BindingSource(dictionary, Nothing)
'Now I can assign the selected value of combobox with this simple command:
cboCombo.SelectedValue = 4
'I can also retrive the selected value with:
value = cboCombo.SelectedValue
If this help you mark as answer

This is just an example of using a dictionary to bind data to a combobox.
Declare dictionary object and initialize it with values as follows:
Dim dcItems As New Dictionary(Of String, Integer)
lstTPAType.Add("Select", -1)
lstTPAType.Add("Item 1", 0)
lstTPAType.Add("Item 2", 1)
lstTPAType.Add("Item ", 2)
cmbMyCombo.DataSource = New BindingSource(dcItems, Nothing)
cmbMyCombo.ValueMember = "Value"
cmbMyCombo.DisplayMember = "Key"
Hope this generic solution will help developers looking for it.

Related

vb,net my collection property in my class is throwing an error

I am learning about collections, I have a Person class
Imports System
Imports System.Collections.Generic
Imports System.Text
Public Class Person
Public Sub New()
End Sub
Public Sub New(ByVal id As Integer, ByVal first_name As String, ByVal mid_name As String, ByVal last_name As String, ByVal age As Short, ByVal sex As Char)
Me.p_id = id
Me.first_name = first_name
Me.mid_name = mid_name
Me.last_name = last_name
Me.p_age = age
Me.p_sex = sex
End Sub
Private p_id As Integer = -1
Private first_name As String = String.Empty
Private mid_name As String = String.Empty
Private last_name As String = String.Empty
Private p_age As Short = 0
Private p_sex As Nullable(Of Char) = Nothing
Public Property ID() As Integer
Get
Return p_id
End Get
Set(ByVal value As Integer)
p_id = value
End Set
End Property
Public Property FirstName() As String
Get
Return first_name
End Get
Set(ByVal value As String)
first_name = value
End Set
End Property
Public Property MiddleName() As String
Get
Return mid_name
End Get
Set(ByVal value As String)
mid_name = value
End Set
End Property
Public Property LastName() As String
Get
Return last_name
End Get
Set(ByVal value As String)
last_name = value
End Set
End Property
Public Property Age() As Short
Get
Return p_age
End Get
Set(ByVal value As Short)
p_age = value
End Set
End Property
Public Property Sex() As Nullable(Of Char)
Get
Return p_sex
End Get
Set(ByVal value As Nullable(Of Char))
p_sex = value
End Set
End Property
End Class
and an Employee Class where I define a Person property
Imports System
Imports System.Collections.Generic
Imports System.Text
Public Class Employee
Public Sub New()
End Sub
Public Sub New(ByVal id As Integer, ByVal companyName As String, ByVal office As String, colPerson As Person)
'Me._employeeid = id
'Me._companyName = companyName
'Me._office = office
End Sub
Private _employeeid As Integer = -1
Private _companyName As String = String.Empty
Private _office As String = String.Empty
Public Property Empoyee_ID() As Integer
Get
Return _employeeid
End Get
Set(ByVal value As Integer)
_employeeid = value
End Set
End Property
Public Property CompanyName() As String
Get
Return _companyName
End Get
Set(ByVal value As String)
_companyName = value
End Set
End Property
Public Property Office() As String
Get
Return _office
End Get
Set(ByVal value As String)
_office = value
End Set
End Property
Property colPerson As List(Of Person)
End Class
How can i populate the persons class as well
Sub Main()
Dim pList As List(Of Person) = New List(Of Person)()
Dim thePerson As New List(Of Person) From
{
New Person With {.Age = 29, .FirstName = "John", .LastName = "Shields", .MiddleName = "", .Sex = "M", .ID = 1},
New Person With {.Age = 34, .FirstName = "Mary", .LastName = "Matthew", .MiddleName = "L", .Sex = "F", .ID = 2},
New Person With {.Age = 55, .FirstName = "Amber", .LastName = "Carl", .MiddleName = "P", .Sex = "M", .ID = 3},
New Person With {.Age = 12, .FirstName = "Kathy", .LastName = "Berry", .MiddleName = "O", .Sex = "F", .ID = 4}
}
'pList.Add(New Person(1, "John", "", "Shields", 29, "M"c))
'pList.Add(New Person(2, "Mary", "Matthew", "Jacobs", 35, "F"c))
'pList.Add(New Person(3, "Amber", "Carl", "Agar", 25, "M"c))
'pList.Add(New Person(4, "Kathy", "", "Berry", 21, "F"c))
'pList.Add(New Person(5, "Lena", "Ashco", "Bilton", 33, "F"c))
'pList.Add(New Person(6, "Susanne", "", "Buck", 45, "F"c))
'pList.Add(New Person(7, "Jim", "", "Brown", 38, "M"c))
'pList.Add(New Person(8, "Jane", "G", "Hooks", 32, "F"c))
'pList.Add(New Person(9, "Robert", "", "", 31, "M"c))
'pList.Add(New Person(10, "Cindy", "Preston", "Fox", 25, "F"c))
'pList.Add(New Person(11, "Gina", "", "Austin", 27, "F"c))
'pList.Add(New Person(12, "Joel", "David", "Benson", 33, "M"c))
'pList.Add(New Person(13, "George", "R", "Douglas", 55, "M"c))
'pList.Add(New Person(14, "Richard", "", "Banks", 22, "M"c))
'pList.Add(New Person(15, "Mary", "C", "Shaw", 39, "F"c))
'
'loop through the list
' PrintOnConsole(pList, "1. --- Looping through all items in the List<T> ---")
'
'Filtering List(T) using a single condition - (Age > 35)
'Dim filterOne As List(Of Person) = pList.FindAll(Function(p As Person) p.Age > 35)
'PrintOnConsole(filterOne, "2. --- Filtering List<T> on single condition (Age > 35) ---")
''
'' Filtering List(T) on multiple conditions (Age > 35 and Sex is Female)
'Dim filterMultiple As List(Of Person) = pList.FindAll(Function(p As Person) p.Age > 35 AndAlso p.Sex = "F"c)
'PrintOnConsole(filterMultiple, "3. --- Filtering List<T> on multiple conditions (Age > 35 and Sex is Female) ---")
''
''Sorting List(T) (Sort on FirstName)
'Dim sortFName As List(Of Person) = pList
'sortFName.Sort(Function(p1 As Person, p2 As Person) p1.FirstName.CompareTo(p2.FirstName))
'PrintOnConsole(sortFName, "4. --- Sort List<T> (Sort on FirstName) ---")
'
'Sorting List(T) descending (Sort on LastName descending)
'Dim sortLNameDesc As List(Of Person) = pList
'sortLNameDesc.Sort(Function(p1 As Person, p2 As Person) p2.LastName.CompareTo(p1.LastName))
'PrintOnConsole(sortLNameDesc, "5. --- Sort List<T> descending (Sort on LastName descending) ---")
''Add new List(T) to existing List(T)
'Dim newList As List(Of Person) = New List(Of Person)()
'newList.Add(New Person(16, "Geoff", "", "Fisher", 29, "M"c))
'newList.Add(New Person(17, "Samantha", "Carl", "Baxer", 32, "F"c))
'pList.AddRange(newList)
'PrintOnConsole(pList, "6. --- Add new List<T> to existing List<> ---")
''Remove multiple items from List(T) based on condition (remove male employees)
'Dim removeList As List(Of Person) = pList
'removeList.RemoveAll(Function(p As Person) p.Sex = "M"c)
'PrintOnConsole(removeList, "7. --- Remove multiple items from List<> based on condition ---")
'' Create Read Only List(T)
'Console.WriteLine("Create Read Only List<>")
'Dim personReadOnly As IList(Of Person) = pList
'Console.WriteLine("Before - Is List Read Only? True or False : " & personReadOnly.IsReadOnly)
'personReadOnly = pList.AsReadOnly()
'Console.WriteLine("After - Is List Read Only? True or False : " & personReadOnly.IsReadOnly & "</br>")
'
'Dim pList1 As New Person
Dim emp As New List(Of Employee)
Dim r As New Employee
r.CompanyName = "zac"
r.Office = "home"
r.Empoyee_ID = 1
'Dim pList1 = New Person(1, "John", "", "Shields", 29, "M"c)
r.colPerson.Add(New Person(1, "John", "", "Shields", 29, "M"c))---> Gives error
emp.Add(r)
'
Dim i As New Employee
i.CompanyName = "zac1"
i.Office = "home1"
i.Empoyee_ID = 2
i.colPerson.Add(New Person(3, "Amber", "Carl", "Agar", 25, "M"c))
pList.Add(New Person(4, "Kathy", "", "Berry", 21, "F"c))
emp.Add(i)
'
Dim t As New Employee
t.CompanyName = "zac2"
t.Office = "home2"
t.Empoyee_ID = 2
pList.Add(New Person(5, "Lena", "Ashco", "Bilton", 33, "F"c))
pList.Add(New Person(6, "Susanne", "", "Buck", 45, "F"c))
emp.Add(t)
For Each item In emp
'item.CompanyName = "zac"
'item.Office = "home"
'item.colperson.Where(Function(x) x.ID = 17)
'Console.WriteLine("employee with person collection: " & item.CompanyName & " " & item.Office & " " & item.colperson.Where(Function(x) x.ID = 17).ToString & "</br>")
Console.WriteLine("employee with person collection: " & item.CompanyName & " " & item.Office & "</br>")
Next
End Sub
r.colPerson.Add(New Person(1, "John", "", "Shields", 29, "M"c))---> Gives error
It gives an error because even though colPerson is declared to be capable of holing a list of people, it hasn't actually been set to be a list of people, so it's currently Nothing, and you can't call methods on something that is Nothing
Property colPerson As New List(Of Person)
^^^
Add a New directive to ensure it's declared and initialized to an instance of a List
Also, please:
Don't put "col" in names
Use a plural name for List(Of Thing) - this is a list of person so it should at least be called People, but also perhaps state what kind of people they are. For example if this Employee was recommended by a few people, call it RcommendedByPeople
Only use Collection in a name if you're writing a class that is a collection, such as Microsoft did when they wrote MatchCollection - a collection of regular expression Matches
Be definite about whether the property is public, private etc
i.e.
Public Property RcommendedByPeople As New List(Of Person)

How to iterate through a VB.net Dictionary Collection

When I iterate through this collection, they key and Province are not in sync. Can someone tell me why ?
Private Sub Button8_Click(sender As Object, e As EventArgs) Handles Button8.Click
Dim Country As Dictionary(Of String, Province)
Country = Module1.CreateCountry
Dim s As String
s = ""
For Each kvp As KeyValuePair(Of String, Province) In Country
s = s + kvp.Key + "; " + kvp.Value.ProvName + "; " + kvp.Value.Region + "; " + kvp.Value.Population + vbCrLf
Next
TextBox4.Text = s
End Sub
Module Module1
Module Module1
Public provinces As CollectionBase
Function CreateCountry() As Dictionary(Of String, Province)
Dim Country As New Dictionary(Of String, Province)
Dim Prov As Province
Prov = New Province
With Prov
.Abbrv = "Qc"
.ProvName = "Quebec"
.Population = "7 500 000"
.Region = "East"
End With
Country.Add(Prov.Abbrv, Prov)
With Prov
.Abbrv = "BC"
.ProvName = "British Columbia"
.Population = "4 500 000"
.Region = "West"
End With
Country.Add(Prov.Abbrv, Prov)
With Prov
.Abbrv = "AB"
.ProvName = "Alberta"
.Population = "5 500 000"
.Region = "Prairies"
End With
Country.Add(Prov.Abbrv, Prov)
With Prov
.Abbrv = "NS"
.ProvName = "Nova Scotia"
.Population = "2 000 000"
.Region = "Maritimes"
End With
Country.Add(Prov.Abbrv, Prov)
Return Country
End Function
End Module
Public Class Province
Public Class Province
Public Property Abbrv As String
Public Property ProvName As String
Public Property Population As String
Public Property Region As String
End Class
Because in the dictionary you add a pointer-reference of Province.
In your case you don't create a new instance of Province but each time you change the properties of the same instance. So when you are done the instance of Province keeps the last values of properties.
For each add, create Country.Add a new instance.
Try this....
Module Module1
Sub Main()
' use a List instead of a Dictionary
Dim Country As New List(Of Province)
' this code adds 4 Province objects to Country List
Country.Add(New Province() With {.Abbrv = "Qc", .Population = "7500000", .ProvName = "Quebec", .Region = "East"})
Country.Add(New Province() With {.Abbrv = "BC", .Population = "4500000", .ProvName = "British Columbia", .Region = "West"})
Country.Add(New Province() With {.Abbrv = "AB", .Population = "5500000", .ProvName = "Alberta", .Region = "Prairies"})
Country.Add(New Province() With {.Abbrv = "NS", .Population = "2000000", .ProvName = "Nova Scotia", .Region = "Maritimes"})
' now you can select any one of the 4 elements in the Country List like so....
Dim prov As Province = (From c In Country Where c.Abbrv = "AB" Select c).FirstOrDefault
End Sub
End Module
Public Class Province
Public Property Abbrv As String
Public Property ProvName As String
Public Property Population As String
Public Property Region As String
End Class
You need to have a grasp of reference types in order to understand and fix the problem.
Long story short, you want four distinct Province instances in your dictionary, all with different property values - but you only ever create one (Prov = New Province), and then keep mutating that same instance and re-adding it to the dictionary. Naturally, what you end up with is a dictionary with 4 KeyValuePairs where the Values all point to the same Province instance.
The solution is to New up a Province instance before setting its property values and adding it to the dictionary, like so:
Function CreateCountry() As Dictionary(Of String, Province)
Dim Country As New Dictionary(Of String, Province)
Dim Prov As Province
Prov = New Province ' Prov now points to instance #1.
With Prov
.Abbrv = "Qc"
.ProvName = "Quebec"
.Population = "7 500 000"
.Region = "East"
End With
Country.Add(Prov.Abbrv, Prov)
Prov = New Province ' Added. Prov now points to instance #2.
With Prov
.Abbrv = "BC"
.ProvName = "British Columbia"
.Population = "4 500 000"
.Region = "West"
End With
Country.Add(Prov.Abbrv, Prov)
Prov = New Province ' Added. Prov now points to instance #3.
With Prov
.Abbrv = "AB"
.ProvName = "Alberta"
.Population = "5 500 000"
.Region = "Prairies"
End With
Country.Add(Prov.Abbrv, Prov)
' Alternative syntax. Prov will point to instance #4.
Prov = New Province With {
.Abbrv = "NS",
.ProvName = "Nova Scotia",
.Population = "2 000 000",
.Region = "Maritimes"
}
Country.Add(Prov.Abbrv, Prov)
Return Country
End Function
Note the alternative initialization syntax for the last Prov instance.

Separate message for condition in vb document

I am creating a seat booking system in visual basic for coursework and it has to allow users to book seats from rows A to E. For row B, I have set it so that there are no seats remaining, however the message simply tells the user that there are not enough seats and that the maximum available seats is 0. I need the code to tell users that there are no seats remaining. My code is as follows:
Public Class Form1
Private Sub ListBox2_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ListBox2.SelectedIndexChanged
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim rowNumber As Integer
Dim SeatsData As String(,) = {{"booked", "A2", "A3", "A4", "A5", "A6", "A7", "A8", "A9", "A10"},
{"booked", "booked", "booked", "booked", "booked", "booked", "booked", "booked", "booked", "booked"},
{"C1", "C2", "C3", "C4", "C5", "C6", "C7", "C8", "C9", "C10"},
{"D1", "booked", "booked", "D4", "D5", "D6", "D7", "D8", "D9", "D10"},
{"E1", "E2", "booked", "booked", "booked", "E6", "E7", "E8", "E9", "E10"}}
If ListBox2.Text = "A" Then
rowNumber = 0
ElseIf ListBox2.Text = "B" Then
rowNumber = 1
ElseIf ListBox2.Text = "C" Then
rowNumber = 2
ElseIf ListBox2.Text = "D" Then
rowNumber = 3
ElseIf ListBox2.Text = "E" Then
rowNumber = 4
End If
FindSeats(rowNumber, ListBox1.Text, SeatsData)
End Sub
Function FindSeats(ByVal RowNumber As Integer, ByVal NumSeats As Integer, SeatsData As Array) As String
Dim i As Integer = 0
Dim arrayPos As Integer = 0
Dim maxSeats As Integer = 0
Dim FirstSeat As String = 0
Dim LastSeat As String = 0
Dim Seatsfound As Boolean = False
Dim returnMsg As String = ""
Do While Seatsfound = False
Dim seatChar As String = SeatsData(RowNumber, arrayPos)
arrayPos = arrayPos + 1
If seatChar = "booked" Then
i = 0
Else
If i = 0 Then
FirstSeat = seatChar
End If
i = i + 1
If i > maxSeats Then
maxSeats = i
End If
End If
If i = NumSeats Then
LastSeat = seatChar
If FirstSeat = LastSeat Then
returnMsg = "Found seat: " + FirstSeat
Else
returnMsg = "Found seats: " + FirstSeat + " - " + LastSeat
End If
MsgBox(returnMsg)
Label3.Text = returnMsg
Seatsfound = True
Exit Do
End If
If arrayPos = 10 Then
returnMsg = "Not enough available seats, maximum available seats: " + CStr(maxSeats)
MsgBox(returnMsg)
Label3.Text = returnMsg
Exit Do
End If
Loop
End Function
End Class
How can I set my code so that it tells the user "there are no remaining seats in this row" or something?
Without using a custom class to design your problem domain, a simple approach is using a Dictionary
For example
Sub Main
Dim seats = new Dictionary(Of string, List(Of String))()
seats.Add("A", new List(Of String) FROM {"A1", "A2", "A3"})
seats.Add("B", new List(Of String) FROM {"booked", "booked", "booked"})
seats.Add("C", new List(Of String) FROM {"C1", "C2", "booked"})
seats.Add("D", new List(Of String) FROM {"booked", "booked", "D3"})
Dim result = FindSeat(seats, "D")
Console.WriteLine(result) ' Output = D3
result = FindSeat(seats, "B")
Console.WriteLine(result) ' Output = "No free seat on that line"
End Sub
Function FindSeat(seats as Dictionary(Of String, List(Of String)), line as String) As String
if seats.ContainsKey(line) Then
dim seatLine = seats(line)
Dim placeFree = seatLine.FirstOrDefault(Function (x) x <> "booked")
if placeFree Is Nothing then
return "No free seat on that line"
else
return placeFree
End If
Else
return "Not a valid line letter"
End If
End Function
In Main, I have statically declared a Dictionary that contains as Key the line letter while a List(Of String) is used as value to declare the seats names and their current state.
Now to find a free seat I get the List(Of String) corresponding to the Line letter and the apply a simple FirstOrDefault to get the first seat not booked

Set selectedindex for comboboxcell in datagridview vb.net

I am trying to set the selectedindex for my datagridviewcomboboxcell through cellvaluechanged event,i.e when i change some value in my datagrid row, this column should get automatically changed. here's the code.
Private Sub DataGridView1_CellValueChanged(sender As Object, e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView1.CellValueChanged
Try
If Me.DataGridView1.Rows(e.RowIndex).Cells(2).Value.ToString <> Nothing Then
Me.DataGridView1("unit_code", e.RowIndex).Value = "1"
MsgBox(Me.DataGridView1.Rows(e.RowIndex).Cells(6).Value)
End If
Else
Exit Sub
End If
End If
Catch ex As Exception
MessageBox.Show(ex.Message, "Message", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
my datagridview is bound to dataset. Searched many sites and did all research, got the above solution where we need to set the valuemember to .value part. Even after doing that it givessystem.formatexception:datagridviewcomboboxcell value is not valid.
Please help me.
[EDIT]
table structure
unit_code descp
0 -
1 nos
2 kgs
3 gms
[EDIT 2]
query = "select Switch(qty=0,'2',qty<=rcvd_qty,'1',rcvd_qty=0,'2',qty>rcvd_qty,'3') as Status,item_type,catalogue,name,pd.rate,qty,pd.unit_code" _
& " from pur_det pd,itemhead th where pd.item_code=th.itemcode and order_no=0 order by catalogue"
adap1 = New OleDbDataAdapter(query, conn)
Dim saldet As New DataSet
adap1.Fill(saldet, "puritems")
Me.DataGridView1.DataSource = saldet.Tables(0)
DataGridView1.Columns.Item(0).HeaderText = "STATUS"
DataGridView1.Columns.Item(0).Width = 68
DataGridView1.Columns.Item(1).HeaderText = "TYPE"
DataGridView1.Columns.Item(1).Width = 60
DataGridView1.Columns.Item(2).HeaderText = "CATALOGUE"
DataGridView1.Columns.Item(2).Width = 140
DataGridView1.Columns.Item(3).HeaderText = "DESCRIPTION"
DataGridView1.Columns.Item(3).Width = 300
DataGridView1.Columns.Item(4).HeaderText = "RATE"
DataGridView1.Columns.Item(4).Width = 60
DataGridView1.Columns.Item(5).HeaderText = "QUANTITY"
DataGridView1.Columns.Item(5).Width = 84
DataGridView1.Columns.Item(6).HeaderText = "UNIT" ' this column is removed below because it only had primary key values of this table("unitmast").
DataGridView1.Columns.Item(6).Width = 70
adap1 = New OleDbDataAdapter("select * from unitmast order by unitcode ASC", conn)
Dim unitc As New DataSet
adap1.Fill(unitc, "unitmast")
Me.DataGridView1.Columns.RemoveAt(6) 'here the same is added with display member to view its actual value
Dim uncol As New DataGridViewComboBoxColumn
With uncol
.Name = "unit_code"
.DataPropertyName = "unit_code"
.DataSource = unitc.Tables(0)
.ValueMember = "unitcode"
.DisplayMember = "desc"
.HeaderText = "UNIT"
.FlatStyle = FlatStyle.Flat
.DropDownWidth = 160
.Width = 70
End With
Me.DataGridView1.Columns.Insert(6, uncol)
A DataGridViewComboBoxCell has no SelectedIndex or SelectedValue property.
You can set the value directly like this:
CType(Me.DataGridView1("unit_code", e.RowIndex), DataGridViewComboBoxCell).Value = "your value string"
Or using the index of the items collection: (this works only if you have not set ValueMember and DisplayMember properties)
Dim combo As DataGridViewComboBoxCell
combo = CType(Me.DataGridView1("unit_code", e.RowIndex), DataGridViewComboBoxCell)
combo.Value = combo.Items('your index')
You can also check a value for nothing like this:
If Not Me.DataGridView1.Rows(e.RowIndex).Cells(2).Value Is Nothing Then
'Your code
End If
I Write and Test that Code For You Good Luck:
Dim Dt As New DataTable
Sub CreateDT()
Dt.Columns.Add("Col1")
Dt.Columns.Add("Col2")
Dt.Rows.Add(New Object(1) {"1", "A"})
Dt.Rows.Add(New Object(1) {"2", "B"})
Dt.Rows.Add(New Object(1) {"3", "C"})
End Sub
Private Sub ChildRibbonForm_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
CreateDT()
'
'Dim CellCol As DataGridViewComboBoxColumn = CType(DataGridView1.Columns(0), DataGridViewComboBoxColumn)
Dim CellCol As New DataGridViewComboBoxColumn
CellCol.Items.Add("Test1")
CellCol.Items.Add("Test2")
CellCol.Items.Add("Test3")
Me.DataGridView1.DataSource = Dt
Me.DataGridView1.Columns.Insert(0, CellCol)
Dim CellBox As DataGridViewComboBoxCell = CType(DataGridView1.Rows(1).Cells(0), DataGridViewComboBoxCell)
'Select the Second Item
CellBox.Value = CellCol.Items(1)
End Sub
'Declare datatable
Dim cdt as new Datatable
'Add columns with types. It is important you specify the type for value member column
cdt.Columns.Add("vm", System.Type.GetType("System.Int32"))
cdt.Columns.Add("dm", System.Type.GetType("System.String"))
'Add items to table
cdt.Rows.Add
cdt.Rows(0).Item(0) = 1
cdt.Rows(0).Item(1) = "Red Cat"
cdt.Rows.Add
cdt.Rows(1).Item(0) = 2
cdt.Rows(1).Item(1) = "Black Cat"
'Add datasource to DataGridViewComboBoxColumn
Dim cc As DataGridViewComboBoxColumn
cc = datagridview1.Columns('colIndex')
cc.DataSource = cdt
cc.ValueMember = "vm"
cc.DisplayMember = "dm"
'Setting then selected value is thus:
Datagridview1.Rows('rowIndex').Cells('colIndex').Value = 2 '2 for black cat
This works for me

How to get Lambda in LINQ to actually filter for dynamic linq

Example-I have a person class
Public Class Person
Private _fname As String
Public Property Fname() As String
Get
Return _fname
End Get
Set(ByVal value As String)
_fname = value
End Set
End Property
Private _lname As String
Public Property Lname() As String
Get
Return _lname
End Get
Set(ByVal value As String)
_lname = value
End Set
End Property
Private _age As Integer
Public Property Age() As Integer
Get
Return _age
End Get
Set(ByVal value As Integer)
_age = value
End Set
End Property
End Class
Dim people As New List(Of Person)
people.Add(New Person With {.Fname = "Alice", .Lname = "Apples", .Age = 1})
people.Add(New Person With {.Fname = "Bob", .Lname = "Banana", .Age = 2})
people.Add(New Person With {.Fname = "Charlie", .Lname = "Cherry", .Age = 3})
people.Add(New Person With {.Fname = "Dave", .Lname = "Durian", .Age = 4})
people.Add(New Person With {.Fname = "Eric", .Lname = "EggPlant", .Age = 10})
Dim filteredPerson = From person In people
filteredPerson.Where(Function(fp) fp.Fname = "Bob")
Dim finalList = filteredPerson.ToList
For Each p In finalList
Debug.Print("FNAME: " + p.Fname)
Next
This still returns all 5 people, like the where is not being applied, what am I doing wrong?
I would also like to be able to pass a list of names and return only those
Dim searchList As New List(Of String)
searchList.Add("Bob")
searchList.Add("Dave")
Dim filteredPerson = From person In people
For Each s In searchList
Dim innerName As String = s
filteredPerson.Where(Function(fp) fp.Fname = innerName)
Next
Dim finalList = filteredPerson.ToList
For Each p In finalList
Debug.Print("FNAME: " + p.Fname)
Next
The problem is that Where doesn't change the collection. It returns the newly filtered collection.
Try this:
Dim filteredPerson = people.Where(Function(fp) fp.Fname = "Bob")
(By the way, I don't see anything dynamic in here... where are you using dynamic LINQ?)
To add multiple Where clauses, you'll want something like this:
Dim searchList As New List(Of String)
searchList.Add("Bob")
searchList.Add("Dave")
Dim filteredPerson As IEnumerable(Of String) = people
For Each s In searchList
Dim innerName As String = s
filteredPerson = filteredPerson.Where(Function(fp) fp.Fname = innerName)
Next
Dim finalList = filteredPerson.ToList
For Each p In finalList
Debug.Print("FNAME: " + p.Fname)
Next
However, I don't believe that's actually what you want to do. Each Where clause is going to insist that Fname is the specified name - and it's not going to be both Bob and Dave! I think you actually want something which can be expressed much more simply:
Dim searchList As New List(Of String)
searchList.Add("Bob")
searchList.Add("Dave")
Dim filteredPerson = people.Where(Function(fp) searchList.Contains(fp.Fname))
Dim finalList = filteredPerson.ToList
For Each p In finalList
Debug.Print("FNAME: " + p.Fname)
Next
All we want to know is whether Fname is in searchList, which is what Contains does.
Dim people As New List(Of Person)
people.Add(New Person With {.Fname = "Alice", .Lname = "Apples", .Age = 1})
people.Add(New Person With {.Fname = "Bob", .Lname = "Banana", .Age = 2})
people.Add(New Person With {.Fname = "Charlie", .Lname = "Cherry", .Age = 3})
people.Add(New Person With {.Fname = "Dave", .Lname = "Durian", .Age = 4})
people.Add(New Person With {.Fname = "Eric", .Lname = "EggPlant", .Age = 10})
Dim searchList As New List(Of String)
searchList.Add("Bob")
searchList.Add("Dave")
dim filteredItems = from p in people _
join i in searchList on p.FName equals i _
select p
dim personFound as Person
for each personFound in filteredItems
Console.WriteLine(personFound.Lname)
next