Solved

WinForms combobox and dataset

Posted on 2004-08-07
19
953 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
  • 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
 

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 500 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
Why You Should Analyze Threat Actor TTPs

After years of analyzing threat actor behavior, it’s become clear that at any given time there are specific tactics, techniques, and procedures (TTPs) that are particularly prevalent. By analyzing and understanding these TTPs, you can dramatically enhance your security program.

 
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

How to improve team productivity

Quip adds documents, spreadsheets, and tasklists to your Slack experience
- Elevate ideas to Quip docs
- Share Quip docs in Slack
- Get notified of changes to your docs
- Available on iOS/Android/Desktop/Web
- Online/Offline

Join & Write a Comment

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.   …
This article describes relatively difficult and non-obvious issues that are likely to arise when creating COM class in Visual Studio and deploying it by professional MSI-authoring tools. It is assumed that the reader is already familiar with the cla…
This video discusses moving either the default database or any database to a new volume.
This video demonstrates how to create an example email signature rule for a department in a company using CodeTwo Exchange Rules. The signature will be inserted beneath users' latest emails in conversations and will be displayed in users' Sent Items…

760 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

Need Help in Real-Time?

Connect with top rated Experts

20 Experts available now in Live!

Get 1:1 Help Now