Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win

x
?
Solved

WinForms combobox and dataset

Posted on 2004-08-07
19
Medium Priority
?
993 Views
Last Modified: 2012-05-05


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?
0
Comment
Question by:sainavya1215
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 11
  • 7
19 Comments
 
LVL 12

Expert Comment

by:roverm
ID: 11743112
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
 
LVL 18

Expert Comment

by:DotNetLover_Baan
ID: 11744385
Hi there...
do this..

Combo1.DataSource = Nothing
Combo1.DataSource = DataSet1
0
 

Author Comment

by:sainavya1215
ID: 11746227
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
Prepare for your VMware VCP6-DCV exam.

Josh Coen and Jason Langer have prepared the latest edition of VCP study guide. Both authors have been working in the IT field for more than a decade, and both hold VMware certifications. This 163-page guide covers all 10 of the exam blueprint sections.

 

Author Comment

by:sainavya1215
ID: 11746229
How do i reload the comBoBox with the database changes if any (as u said clear it and then refill it again)
0
 
LVL 12

Expert Comment

by:roverm
ID: 11746325
   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
 

Author Comment

by:sainavya1215
ID: 11751001
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
 
LVL 12

Accepted Solution

by:
roverm earned 2000 total points
ID: 11751170
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
 

Author Comment

by:sainavya1215
ID: 11755046
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
 

Author Comment

by:sainavya1215
ID: 11755069
after clearing the combo we can refill the Fresh data in combo using PopulateCombo()
0
 
LVL 12

Expert Comment

by:roverm
ID: 11759889
You are NOT bounding the combobox to a class, you ARE manually filling it because you loop thru the records.
0
 

Author Comment

by:sainavya1215
ID: 11760214
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
 
LVL 12

Expert Comment

by:roverm
ID: 11760509
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
 

Author Comment

by:sainavya1215
ID: 11767168
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
 
LVL 12

Expert Comment

by:roverm
ID: 11770068
Yes
0
 

Author Comment

by:sainavya1215
ID: 11770181
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
 

Author Comment

by:sainavya1215
ID: 11770379
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
 
LVL 12

Expert Comment

by:roverm
ID: 11770564
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
 

Author Comment

by:sainavya1215
ID: 11772412
ok let me try it out again and I will let u know the update......Thanks roverm
0
 

Author Comment

by:sainavya1215
ID: 11799450
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

Featured Post

Keep up with what's happening at Experts Exchange!

Sign up to receive Decoded, a new monthly digest with product updates, feature release info, continuing education opportunities, and more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

IP addresses can be stored in a database in any of several ways.  These ways may vary based on the volume of the data.  I was dealing with quite a large amount of data for user authentication purpose, and needed a way to minimize the storage.   …
In my previous two articles we discussed Binary Serialization (http://www.experts-exchange.com/A_4362.html) and XML Serialization (http://www.experts-exchange.com/A_4425.html). In this article we will try to know more about SOAP (Simple Object Acces…
Video by: ITPro.TV
In this episode Don builds upon the troubleshooting techniques by demonstrating how to properly monitor a vSphere deployment to detect problems before they occur. He begins the show using tools found within the vSphere suite as ends the show demonst…
In this video, Percona Director of Solution Engineering Jon Tobin discusses the function and features of Percona Server for MongoDB. How Percona can help Percona can help you determine if Percona Server for MongoDB is the right solution for …

618 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question