Binding Label and Value to ComboBox Winforms
I have this code
Public Sub FillCategoryCombobox(ByVal categoryList As List(Of tblCategory), ByVal LvName As ComboBox)
LvName.Items.Clear()
Dim itemValue 开发者_开发技巧= New Dictionary(Of Integer, String)()
For Each category As tblCategory In categoryList
itemValue.Add(category.CategoryID, category.CategoryName)
Next category
LvName.DataSource = New BindingSource(itemValue, Nothing)
LvName.DisplayMember = "Value"
LvName.ValueMember = "Key"
End Sub
I receive an error on
LvName.DataSource = New BindingSource(itemValue, Nothing)
Value cannot be null
You can bind a dictionary to a datasource by using the ToList() method of the dictionary.
Edit
Some code:
LvName.DataSource = itemValue.ToList()
LvName.DisplayMember = "Value"
LvName.ValueMember = "Key"
Never ever tried to bind a dictionary to a control's datasource or bindingsource. Maybe that's not possible. Why don't you use your categoryList as a DataSource (for the BindingSource or directly)
combo1.DataSource = categoryList
combo1.DisplayMember = "CategoryName"
combo1.ValueMember = "CategoryID"
or if you need to maintain the position:
dim bs as new BindingSource(categoryList, nothing)
combo1.DataSource = bs
combo1.DisplayMember = "CategoryName"
combo1.ValueMember = "CategoryID"
or create a List(of category)
instead of a Dictionary.
btw. a full stack trace is always helpfull.
Do you need the BindingSource? If not you can set the ComboBox DataSource to your list directly. And instead of using a dictionary you can use something simpler like a KeyValuePair.
Can you try the following:
KeyValuePair[] pairs = new KeyValuePair[0];
ComboBox box = new ComboBox();
box.DisplayMember = "Value";
box.ValueMember = "Key";
box.DataSource = pairs;
精彩评论