WinForms combobox and dataset



i have a Windows Form comboBox at the client. I have a Dll which uses function to return a dataset to the client.
i use the function at the client looping thru dataTable/rows and fill up comboBox in the FORM_LOAD() EVENT.

Lets say we update the database table with an additional row . I want the data in comboBox to be updated too.

Should It be implemented in combBox_selectedIndex changed event. If so i  tried refilling the combobox in selectedIndex changed event . I get duplicate records.
How can this be achieved?
sainavya1215Asked:
Who is Participating?
 
rovermConnect With a Mentor Commented:
Since you are returning a fresh datatable simply clear the combo first:

ComboBox.Items.Clear

So:

Dim  obj  As New CStock
        Try
            Dim Dt As New DataTable
            Dt =obj.FillCombo (Returns a datatable from the class CSTock)
           comboBox.Items.Add(New CStock("-------------Select-----------------", "0"))
            Dim dr As DataRow
            comboBox.Items.Clear '**************** here's the new line ****************
            For Each dr In Dt.Rows
                Dim objItem = New Cstock(dr.Item(0).ToString(), CInt(dr.Item(1)))
                comboBox.Items.Add(objItem)
            Next
        Catch ex As Exception
            MessageBox.Show(ex.Message.ToString)
        Finally
            obj = Nothing
        End Try
0
 
rovermCommented:
First of all, why do you loop thru the records?
Simply set the datasource to the dataset:

Combo1.DataSource = DataSet1

But, if you want to refill your combo, just clear it first:

Combo1.Items.Clear

D'Mzz!
RoverM
0
 
DotNetLover_BaanCommented:
Hi there...
do this..

Combo1.DataSource = Nothing
Combo1.DataSource = DataSet1
0
Get your problem seen by more experts

Be seen. Boost your question’s priority for more expert views and faster solutions

 
sainavya1215Author Commented:
Well this was the method first used in the DLL (Datasource) but it was disapproved as I am using .NET remoting. So the best way to populate the Combo in this scenario is to return a DataTable or a Dataset to the client from remoteServer.

I populate the comboBox using code below in the CLIENT App :

  Dim  obj  As New CStock
        Try
            Dim Dt As New DataTable
            Dt =obj.FillCombo (Returns a datatable from the class CSTock)
           comboBox.Items.Add(New CStock("-------------Select-----------------", "0"))
            Dim dr As DataRow
            For Each dr In Dt.Rows
                Dim objItem = New Cstock(dr.Item(0).ToString(), CInt(dr.Item(1)))
                comboBox.Items.Add(objItem)
            Next
        Catch ex As Exception
            MessageBox.Show(ex.Message.ToString)
        Finally
            obj = Nothing
        End Try
0
 
sainavya1215Author Commented:
How do i reload the comBoBox with the database changes if any (as u said clear it and then refill it again)
0
 
rovermCommented:
   Private Sub FillCombo()
        Dim ds As DataSet = yourclass.fillcombo 'make sure to return a dataset!!!
        ComboBox1.DataSource = Nothing
        ComboBox1.DataSource = ds
        ComboBox1.ValueMember = "yourvaluefield"
        ComboBox1.DisplayMember = "yourdisplayfield"
    End Sub

Call this every time you want to (re)load your combo.

D'Mzz!
RoverM
0
 
sainavya1215Author Commented:
Hi,
I have to change a lot of code if i need to implement this in many classes. I have already working functionality given below
i just need to know how I can fill up the fresh data in the comboBox in the selectedindexChanged event of combo using the following
Code which works


THE ITEM SELECTED in the comboBox is retrieved using
    Private Sub  combobox_SelectedIndexChanged2(ByVal sender As Object, ByVal e As System.EventArgs) Handles combobox.SelectedIndexChanged
                        ItemSelected = CType(comboBox.SelectedItem, Cstock).stockID    'Returns stock_ID of item selected frrom comboBox


  DLL code
=============================================================  
Public class Cstock
Public Function FillCombos() As DataTable
        dim oDb as new CdbConn
        Dim ObjDs As New DataSet
        Dim SqlAdapter As SqlClient.SqlDataAdapter
        Dim mCommand As New SqlClient.SqlCommand
        Try
            mCommand.Connection = odb.Open
            mCommand.CommandType = CommandType.StoredProcedure
            mCommand.CommandText = "sp_loadStock"
            SqlAdapter = New SqlClient.SqlDataAdapter
            SqlAdapter.SelectCommand = mCommand
            SqlAdapter.Fill(ObjDs, "stock")
            mCommand.ExecuteNonQuery()
            Dim stock As New DataTable
            stock.Columns.Add("stock_desc", GetType(System.String))
            stock.Columns.Add(stock_id", GetType(System.String))
            '
            Dim drDSRow As DataRow
            Dim drNewRow As DataRow
            For Each drDSRow In ObjDs.Tables("Codes").Rows()
                drNewRow = dtseries.NewRow()
                drNewRow("stock_desc") = drDSRow("stock_desc")
                drNewRow("stock_id") = drDSRow("stock_id")
                stock.Rows.Add(drNewRow)
            Next
            Return stock
        Catch Ex As Exception
            throw ex
        End Try
    End Function
End class
======================================================================
Client
===============================
I populate the comboBox using code below in the CLIENT App :

  Dim  obj  As New CStock
        Try
            Dim Dt As New DataTable
            Dt =obj.FillCombo (Returns a datatable from the class CSTock)
           comboBox.Items.Add(New CStock("-------------Select-----------------", "0"))
            Dim dr As DataRow
            For Each dr In Dt.Rows
                Dim objItem = New Cstock(dr.Item(0).ToString(), CInt(dr.Item(1)))
                comboBox.Items.Add(objItem)
            Next
        Catch ex As Exception
            MessageBox.Show(ex.Message.ToString)
        Finally
            obj = Nothing
        End Try
0
 
sainavya1215Author Commented:
hi rovern,
The comboBox has already items being added using Cstock class
would u think combo.items.clear would work......Data in combo is bound to a class right. combo.Items.clear would work if ur adding data manually like

combobox.items.add("k")
comboBox.items.add("p")
combobox.items.clear()

There should be a way to clear the contents might be databTable or the class contents In SelectedIndexChanged Event as per the above code.
0
 
sainavya1215Author Commented:
after clearing the combo we can refill the Fresh data in combo using PopulateCombo()
0
 
rovermCommented:
You are NOT bounding the combobox to a class, you ARE manually filling it because you loop thru the records.
0
 
sainavya1215Author Commented:
Roverm,
i used combobox.items.clear in Populatecombo function ........While debugging it works fine ........I called the populateCombo Function in the selectedIndexChanged event of comboBox so that it would refilll... I get the error "Object instance not set to instance of an object"  when i try to select value from comboBox

(This code was  working earlier Before  ComboBox.items.clear was used in PopulateCombo function )

Private sub comboBox_SelectedIndexChanged2(ByVal sender As Object, ByVal e As System.EventArgs) Handles comboBox.SelectedIndexChanged
  If comboBox.SelectedIndex <> 0 Then
                Dim ItemSelected As Integer
                ItemSelected = CType(ComboBox.SelectedItem, cStock).stockID
                MsgBox(ItemSelected)
end if

Thanks in advance
 
0
 
rovermCommented:
If you are refilling the combobox BEFORE reading its value then yes, it will give the error.

So: first readback the value, then clear:

Private sub comboBox_SelectedIndexChanged2(ByVal sender As Object, ByVal e As System.EventArgs) Handles comboBox.SelectedIndexChanged
  If comboBox.SelectedIndex <> 0 Then
                Dim ItemSelected As Integer
                ItemSelected = CType(ComboBox.SelectedItem, cStock).stockID
                MsgBox(ItemSelected)
                Combobox.Items.Clear
end if

This should work fine.

D'Mzz!
RoverM
0
 
sainavya1215Author Commented:
Does this mean that I have to call the populatecombo after comboBox.items.clear ???

Private sub comboBox_SelectedIndexChanged2(ByVal sender As Object, ByVal e As System.EventArgs) Handles comboBox.SelectedIndexChanged
  If comboBox.SelectedIndex <> 0 Then
                Dim ItemSelected As Integer
                ItemSelected = CType(ComboBox.SelectedItem, cStock).stockID
                MsgBox(ItemSelected)
                Combobox.Items.Clear
                PopulateCombo()  'AFter clearing the combo  REFILL combo ---------------------
end if
0
 
rovermCommented:
Yes
0
 
sainavya1215Author Commented:
rover,

As I want the comboBox to refresh when IndexChanged  ....I just commented out all other code to check whether the New data is being shown to make it simpler

a)Clearcombo b) RefillCombo

form_load()
PopulateCombo()

Private sub Populatecombo()
Dim  obj  As New CStock
        Try
            Dim Dt As New DataTable
            Dt =obj.FillCombo (Returns a datatable from the class CSTock)
           comboBox.Items.Add(New CStock("-------------Select-----------------", "0"))
            Dim dr As DataRow
            For Each dr In Dt.Rows
                Dim objItem = New Cstock(dr.Item(0).ToString(), CInt(dr.Item(1)))
                comboBox.Items.Add(objItem)
            Next
        Catch ex As Exception
            MessageBox.Show(ex.Message.ToString)
        Finally
            obj = Nothing
        End Try
End sub

Private sub comboBox_SelectedIndexChanged2(ByVal sender As Object, ByVal e As System.EventArgs) Handles comboBox.SelectedIndexChanged
ComboBox.items.clear  
PopulateCombo()
 
I have 2 problems here

1) when I selected an item it is not getting Selected in ComboBox
 2)I added a New Record and selectedComboBOx again .....It doesnot display the new record in the combo

0
 
sainavya1215Author Commented:
I ALSO Tried as u said   Return DataTable to the client application  and bind it over there..I can see the comboBox Filled but when i add new record and selected combo value is not in there. when I close the form and open it again then i can see......but thats not what we want.......

I dont understand how to Overcome this problem


 Dim objStock As New Cstock
        Dim dt As New DataTable
        dt =ObjStock.returnDataTable()
       comboBox.DataSource = dt
        comboBox.DisplayMember = "stock_desc"
      comboBox.ValueMember = "stock_id"


form_load
call bindCombo()
0
 
rovermCommented:
When you try databinding then you need to set the datasource to nothing first, then rebind it.

I don't understand this:
1) when I selected an item it is not getting Selected in ComboBox

What do you mean?
0
 
sainavya1215Author Commented:
ok let me try it out again and I will let u know the update......Thanks roverm
0
 
sainavya1215Author Commented:
Hi Roverm,

Solved the prob using combobox.items.clear as mentioned earlier and called the sub in click event of combo to refill the combo with fresh data

Thx for the help
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.