473,715 Members | 2,162 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Fill a Combo box with a data reader

Has anyone an example of filling a combo box with a data reader?
Thanks
Vayse
Nov 23 '05 #1
18 20227
Here's one; you'll need at the top of your class code:
Imports System.Data.Ole Db

Private Sub Form1_Load(ByVa l sender As Object, _
ByVal e As EventArgs) Handles MyBase.Load
Try
Dim dbpath As String = "c:\t\db1.m db"
Dim dbConn As New OleDbConnection ( _
"Provider=Micro soft.Jet.OLEDB. 4.0;DATA SOURCE=" & dbpath)
dbConn.Open()
Dim dbCommand As New OleDbCommand( _
"SELECT * FROM Customers", dbConn)
Dim dbDR As OleDb.OleDbData Reader = dbCommand.Execu teReader
Do While dbDR.Read
ComboBox1.Items .Add(dbDR("CUSC ODE"))
Loop
Catch ex As Exception
MessageBox.Show (ex.Message & vbCrLf & ex.StackTrace, "Error")
End Try
End Sub

Nov 23 '05 #2
Just to add to KitWest's excellent code, I would create a "ListBoxIte m"
class so that you can store both a value and displayitem.

Greg

Imports System.Data.Ole Db
Public Class Form1

Private Sub Form1_Load(ByVa l sender As System.Object, ByVal e As
System.EventArg s) Handles MyBase.Load
Try
Dim dbpath As String = "c:\t\db1.m db"
Dim dbConn As New OleDbConnection ( _
"Provider=Micro soft.Jet.OLEDB. 4.0;DATA SOURCE=" & dbpath)
dbConn.Open()
Dim dbCommand As New OleDbCommand( _
"SELECT * FROM Customers", dbConn)
Dim dbDR As OleDb.OleDbData Reader = dbCommand.Execu teReader

ComboBox1.Begin Update()

Do While dbDR.Read
ComboBox1.Items .Add(New ListBoxItem(Cin t(dbDR("CUSCODE ")),
dbDR("CUSNAME") .ToString))
Loop

ComboBox1.EndUp date()

Catch ex As Exception
MessageBox.Show (ex.Message & vbCrLf & ex.StackTrace, "Error")
End Try
End Sub

End Class

Public Class ListBoxItem

Private listItemData As Object
Private listItemText As String

' This is what is displayed in the ComboBox drop-down
Public Overrides Function ToString() As String
Return listItemText
End Function

Public Sub New(ByVal itemData As Object, ByVal itemText As String)

listItemData = itemData
listItemText = itemText
End Sub

Public ReadOnly Property Data() As Object
Get
Data = listItemData
End Get

End Property

Public ReadOnly Property Text() As String
Get
Text = listItemText
End Get

End Property

End Class
Nov 23 '05 #3
Thanks guys.
Another question on this.
Theres several combo boxes on this form, so for speed reasons I'd like to
remove the table adapters and binding sources, and just use Data readers.

Me.CostCentresT ableAdapter.Fil l(Me.AssetsData Set.CostCentres )

So I have a databound comCostCentres with these properties
DateSource = CostCentresBind ingSource
Display Member = CostName
Display Value = CostCode
Selectecd Value = AssetsBindingSo urce - CostCentre

I have the combo box filling correctly, thanks to your code. But it doesn't
display the select CostCentre correctly, and its not updating the Asset.
What step am I missing?
Thanks
Vayse
Try

' Fill the combo boxes
Me.comCostCentr e.DisplayMember = "CostName"
Me.comCostCentr e.ValueMember = "CostCode"

Dim dbConn As New OleDbConnection (conCONNECT)
dbConn.Open()

Dim dbCommand As New OleDbCommand("S ELECT * FROM CostCentres",
dbConn)
Dim dbDR As OleDb.OleDbData Reader = dbCommand.Execu teReader

comCostCentre.B eginUpdate()

Do While dbDR.Read
comCostCentre.I tems.Add(New ListBoxItem(dbD R("CostCode") ,
dbDR("CostName" )))
Loop

comCostCentre.E ndUpdate()

dbDR.Close()
dbConn.Close()

Catch ex As Exception
MessageBox.Show (ex.Message & vbCrLf & ex.StackTrace, "Error")
End Try


"Greg Burns" <bl*******@news groups.nospam> wrote in message
news:e6******** ******@TK2MSFTN GP09.phx.gbl...
Just to add to KitWest's excellent code, I would create a "ListBoxIte m"
class so that you can store both a value and displayitem.

Greg

Nov 23 '05 #4
Just to make it clear - I've removed the CostCentresTabl eAdapter and those
databound properties. Thats as they were before I used the Datareader.

"Vayse" <Va***@nospam.n ospam> wrote in message
news:%2******** ********@TK2MSF TNGP10.phx.gbl. ..
Thanks guys.
Another question on this.
Theres several combo boxes on this form, so for speed reasons I'd like to
remove the table adapters and binding sources, and just use Data readers.

Me.CostCentresT ableAdapter.Fil l(Me.AssetsData Set.CostCentres )

So I have a databound comCostCentres with these properties
DateSource = CostCentresBind ingSource
Display Member = CostName
Display Value = CostCode
Selectecd Value = AssetsBindingSo urce - CostCentre

I have the combo box filling correctly, thanks to your code. But it
doesn't display the select CostCentre correctly, and its not updating the
Asset.
What step am I missing?
Thanks
Vayse
Try

' Fill the combo boxes
Me.comCostCentr e.DisplayMember = "CostName"
Me.comCostCentr e.ValueMember = "CostCode"

Dim dbConn As New OleDbConnection (conCONNECT)
dbConn.Open()

Dim dbCommand As New OleDbCommand("S ELECT * FROM CostCentres",
dbConn)
Dim dbDR As OleDb.OleDbData Reader = dbCommand.Execu teReader

comCostCentre.B eginUpdate()

Do While dbDR.Read
comCostCentre.I tems.Add(New ListBoxItem(dbD R("CostCode") ,
dbDR("CostName" )))
Loop

comCostCentre.E ndUpdate()

dbDR.Close()
dbConn.Close()

Catch ex As Exception
MessageBox.Show (ex.Message & vbCrLf & ex.StackTrace, "Error")
End Try


"Greg Burns" <bl*******@news groups.nospam> wrote in message
news:e6******** ******@TK2MSFTN GP09.phx.gbl...
Just to add to KitWest's excellent code, I would create a "ListBoxIte m"
class so that you can store both a value and displayitem.

Greg


Nov 23 '05 #5
"Vayse" <Va***@nospam.n ospam> wrote in message
news:%2******** ********@TK2MSF TNGP10.phx.gbl. ..
Selectecd Value = AssetsBindingSo urce - CostCentre

I have the combo box filling correctly, thanks to your code. But it
doesn't display the select CostCentre correctly, and its not updating the
Asset.
What step am I missing?


I am not sure I follow, but here is some more code I use:

' set the combobox to a default display text
' this seems to automagically set the selected value as well
comCostCentre.T ext = "a CostName is the list"

' how to retrieve the value
Dim value as string = CType(comCostCe ntre.SelectedIt em,
ListBoxItem).Da ta.ToString

HTH,
Greg
Nov 23 '05 #6

"Vayse" <Va***@nospam.n ospam> wrote in message
news:e1******** *****@TK2MSFTNG P11.phx.gbl...
Just to make it clear - I've removed the CostCentresTabl eAdapter and those
databound properties. Thats as they were before I used the Datareader.

"Vayse" <Va***@nospam.n ospam> wrote in message
news:%2******** ********@TK2MSF TNGP10.phx.gbl. ..
Thanks guys.
Another question on this.
Theres several combo boxes on this form, so for speed reasons I'd like to
remove the table adapters and binding sources, and just use Data readers.

Me.CostCentresT ableAdapter.Fil l(Me.AssetsData Set.CostCentres )

So I have a databound comCostCentres with these properties
DateSource = CostCentresBind ingSource
Display Member = CostName
Display Value = CostCode
Selectecd Value = AssetsBindingSo urce - CostCentre

I have the combo box filling correctly, thanks to your code. But it
doesn't display the select CostCentre correctly, and its not updating the
Asset.
What step am I missing?


I guess I don't know your problem domain well enough. I see you have a
combobox name comConstCentres (I assume this contain costcenters, with
Name/Value pairs; CostName/CostCode). What do you mean when you say "its
not updating the Asset". I would take it to mean, setting the selected
value on your combobox is not sticking.?

I know you are not using the above code anymore, but what in the world did
the below line do? :)

Selectecd Value = AssetsBindingSo urce - CostCentre

What does it mean to be using a subtractation between objects here?

Greg
Nov 23 '05 #7
Selected Value = AssetsBindingSo urce - CostCentre

If you look at the property, thats the way its displayed! Not a calculation
or anything, just means Assets.CostCent re
Also displayed that way if you click the smart tag. Kind of strange really.

And yes, the selected value in the combo box is not sticking. Also, its not
been filled correctly.
So when I navigate to a new record, the combo box is blank.

"Greg Burns" <bl*******@news groups.nospam> wrote in message
news:%2******** ********@TK2MSF TNGP09.phx.gbl. ..

"Vayse" <Va***@nospam.n ospam> wrote in message
news:e1******** *****@TK2MSFTNG P11.phx.gbl...
Just to make it clear - I've removed the CostCentresTabl eAdapter and
those databound properties. Thats as they were before I used the
Datareader.

"Vayse" <Va***@nospam.n ospam> wrote in message
news:%2******** ********@TK2MSF TNGP10.phx.gbl. ..
Thanks guys.
Another question on this.
Theres several combo boxes on this form, so for speed reasons I'd like
to remove the table adapters and binding sources, and just use Data
readers.

Me.CostCentresT ableAdapter.Fil l(Me.AssetsData Set.CostCentres )

So I have a databound comCostCentres with these properties
DateSource = CostCentresBind ingSource
Display Member = CostName
Display Value = CostCode
Selectecd Value = AssetsBindingSo urce - CostCentre

I have the combo box filling correctly, thanks to your code. But it
doesn't display the select CostCentre correctly, and its not updating
the Asset.
What step am I missing?


I guess I don't know your problem domain well enough. I see you have a
combobox name comConstCentres (I assume this contain costcenters, with
Name/Value pairs; CostName/CostCode). What do you mean when you say "its
not updating the Asset". I would take it to mean, setting the selected
value on your combobox is not sticking.?

I know you are not using the above code anymore, but what in the world did
the below line do? :)

Selectecd Value = AssetsBindingSo urce - CostCentre

What does it mean to be using a subtractation between objects here?

Greg

Nov 23 '05 #8
"Vayse" <Va***@nospam.n ospam> wrote in message
news:OP******** *****@TK2MSFTNG P10.phx.gbl...
Selected Value = AssetsBindingSo urce - CostCentre

If you look at the property, thats the way its displayed! Not a
calculation or anything, just means Assets.CostCent re
Also displayed that way if you click the smart tag. Kind of strange
really.

And yes, the selected value in the combo box is not sticking. Also, its
not been filled correctly.
So when I navigate to a new record, the combo box is blank.


That sounds like you are still using DataBinding. I am not sure you can
manually populate a combobox like that and have databinding still function.

Hopefully somebody else has some ideas.

Greg


Nov 23 '05 #9
Yeah, I'm still using databinding on the form. Just wanted to "kind of"
unbind the combo boxes. I thought it would be possible.

Thanks for your help though - very useful for all my other forms, which
aren't data bound. And I'm beginning to regret ever making this form data
bound!

"Greg Burns" <bl*******@news groups.nospam> wrote in message
news:eY******** ******@TK2MSFTN GP12.phx.gbl...
"Vayse" <Va***@nospam.n ospam> wrote in message
news:OP******** *****@TK2MSFTNG P10.phx.gbl...
Selected Value = AssetsBindingSo urce - CostCentre

If you look at the property, thats the way its displayed! Not a
calculation or anything, just means Assets.CostCent re
Also displayed that way if you click the smart tag. Kind of strange
really.

And yes, the selected value in the combo box is not sticking. Also, its
not been filled correctly.
So when I navigate to a new record, the combo box is blank.


That sounds like you are still using DataBinding. I am not sure you can
manually populate a combobox like that and have databinding still
function.

Hopefully somebody else has some ideas.

Greg

Nov 23 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
1319
by: Mike P | last post by:
I'm using 1 connection to open 3 separate data readers to read data into 3 data grids. However, when I try to use the 2nd reader it says that the first reader must be closed. So I use Close() to close it and now it says that 'Object reference not set to an instance of an object' on that line of code. Can anybody help me out with this? SqlConnection objConnection = new SqlConnection(ConfigurationSettings.AppSettings );
1
1700
by: mhnazly | last post by:
i'm trying to read data from SQL Server database using data reader and assigned it to a label in my asp.net web application. but when the button is clicked, nothing appears. please help, thanks. Private Sub btnTesting_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnTesting.Click Dim cn As New SqlClient.SqlConnection Dim cm As New SqlClient.SqlCommand
1
1257
by: atif | last post by:
hi i hav a prob with data reader. i hav a 2 column in a data table n i hav 2 drop down lists on my page. Now i want to connect my first drop down with the first column of the data table. Though i got the result frm the following code dim ee as System.Data.IDataReader = returnCategory() dropdownlist1.DataSource = ee dropdownlist1.DataBind()
4
1731
by: Ram | last post by:
I am using ADO.Net data reader to retrieve data from main frame. I am getting timestamp which is 26 (yyyy-mm-dd hh- mm-ss.123456) bytes as sqltimestamp data type. I am using data reader to retrieve this values and when i get it from data reader it is coverting as (yyyy-mm-dd hh-mm-ss AM or PM) and drops milliseconds. If any one of you come across this problem pls let me know how u have handled this situation.
6
1474
by: Jim Heavey | last post by:
I am new to SqlServer, have been using Oracle in a prior life. I have written a very simple stored procedure in SQL Server and it (the query) looks like the following... Select AD_ID, First_Name, Last_Name, User_Type, Phone_Nbr, Email_Addr From dbo.User_Tbl Where UPPER(AD_ID) = UPPER(@AD_ID) and UPPER(User_Type) = UPPER(@User_Type)
1
1466
by: simonZ | last post by:
I have data reader(I can't create data adapter, because I'm using command.BeginExecuteReader and EndExecuteReader) What is the best way to save data reader to table inside the data set? Any example? Thanks, Simon
3
2701
by: =?Utf-8?B?cm9kY2hhcg==?= | last post by:
hey all, how do you resolve this problem? i have a public procedure in my DataAccessLayer that gets a SqlDataReader how do i close the reader from inside the DataAccessLayer if I'm returning the reader to get bound to my GridView? Any code after my return will be unreachable. thanks,
3
1801
by: charvi | last post by:
i hae a ole data reader which contains records extracted from Query.how can i check for end of file in data reader.and i want to know the number of records present in data reader thanks in advance
0
9193
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
7966
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6641
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5964
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4472
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4734
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3171
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2532
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2116
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.