populating dropdown in windows forms

svibuk

Active member
Joined
Jul 15, 2008
Messages
31
Programming Experience
1-3
i have a form with a dropdown
i am populating dropdowmn from database but having few issues

i have a sub function fr populating the dropdown as
Dim da1 As New SqlDataAdapter(cmd1)
Dim ds1 As New DataSet()
da1.Fill(ds1, "M_customer")
Me.drpcust.DataSource = ds1

Me.drpcust.DisplayMember = "Cname"
Me.drpcust.ValueMember = "CID"

but after this line Me.drpcust.DataSource = ds1 the prg flow jumps to another sub function
having If drpcust.SelectedIndex = -1 Then

cmdsave.Enabled = False
Button1.Enabled = False
which shld not happen
and even he dropdown is not getting populated
 
The problem is that you are populating a single DataTable in the DataSet but you then don't tell the ComboBox anything about the DataTable, so it doesn't know where to get the data from. If you want to use a DataSet then you have to either get the DataTable from the DataSet and bind that, or else bind the DataSet and then qualify the column names with the table name when setting the DisplayMember and ValueMember.

That said, what's the point of the DataSet anyway? If all you want to do is populate a single DataTable then why not just create a DataTable in the first place?

On a different note, while it's not too big a deal, it is preferable to set the DisplayMember and ValueMember before setting the DataSource.
 
i have a form with a dropdown
i am populating dropdowmn from database but having few issues

i have a sub function fr populating the dropdown as
Dim da1 As New SqlDataAdapter(cmd1)
Dim ds1 As New DataSet()
da1.Fill(ds1, "M_customer")
Me.drpcust.DataSource = ds1

Me.drpcust.DisplayMember = "Cname"
Me.drpcust.ValueMember = "CID"

but after this line Me.drpcust.DataSource = ds1 the prg flow jumps to another sub function
having If drpcust.SelectedIndex = -1 Then

cmdsave.Enabled = False
Button1.Enabled = False
which shld not happen
and even he dropdown is not getting populated



ok but why is the flow shifting from one sub event to another ?
 
Because when you bind a list to a control, the first item in that list is selected. Before binding there are no items so no item is selected and after binding the first item is selected so obviously the SelectedIndex must have changed, therefore the SelectedIndexChanged event will be raised. If you don't want to do anything under those circumstances then, with a ComboBox, the obvious option is to handle the SelectionChangeCommitted event, which is raised only when the user changes the selection, rather than the SelectedIndexChanged event..
 
Back
Top