using VS2005 - VB.Net
I noticed unexpected behaviour when using a combobox which has it's
datasource set to a datatable. Also the Valuemember and Displaymember are
being set. I'm getting a cast error when trying to read the SelectedValue.
However, if I change the order in which DataSource, Valuemember and
Displaymemeber are set, then the cast error is not thrown. What is happening
here?
Example (the error appears at ***) where ID is an integer, Name is a string:
Public Class FrmTestComboBox
Private Sub FrmTestComboBox _Load(ByVal sender As System.Object, ByVal e
As System.EventArg s) Handles MyBase.Load
FillCombo()
End Sub
Public Sub FillCombo()
ComboBox1.DataS ource = MyTable
ComboBox1.Value Member = "ID"
ComboBox1.Displ ayMember = "Name"
End Sub
Private Sub ComboBox1_Selec tedIndexChanged (ByVal sender As
System.Object, ByVal e As System.EventArg s) Handles
ComboBox1.Selec tedIndexChanged
Dim val As Integer
Dim row As DataRowView
If ComboBox1.Selec tedIndex -1 Then
*** val = CInt(ComboBox1. SelectedValue)
row = DirectCast(Comb oBox1.SelectedI tem, DataRowView)
Label1.Text = CStr(row("Name" ))
End If
End Sub
End Class
If I rewrite this (setting DataSource as the last line), it works as expected.
Public Sub FillCombo()
ComboBox1.Value Member = "ID"
ComboBox1.Displ ayMember = "Name"
ComboBox1.DataS ource = MyTable
End Sub
I did not expect the order of the lines of code would have any consequence
here ...
Also in the Documentation an example shows up (for a listbox) which first
sets the datasource, and then the valuemember and displaymember.
ms-help://MS.VSCC.v80/MS.MSDN.v80/MS.NETDEVFX.v20 .en/CPref17/html/P_System_Window s_Forms_ListCon trol_ValueMembe r.htm
Martin
--
It''s Software Jim, but not as we know it!