Saturday, March 24, 2012

Simple data binding question

Hi, i'm trying to write a simple app to read a column in access and bind it to a windows forms combo box. This is my code

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'Load list of countys into combo1
Dim myConn As New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0; data source=C:\postcodedb\postcode.mdb")
Dim SQL As String = "SELECT DISTINCT (cnt) FROM postcode"
Dim Rdr As OleDbDataReader
Dim Cmd As New OleDbCommand(SQL, myConn)
Try
myConn.Open()
Catch ex As Exception
MessageBox.Show(ex.ToString)
Rdr = Cmd.ExecuteReader
ComboBox1.DataSource = Rdr
ComboBox1.DisplayMember = ("cnt")
Finally
myConn.Close()

It doesn't work, no errors but the countys dont appear in the combo - what have I done wrong.

Thanks
Ben
End Try
End SubAlthough this is really a windows forms application rather than ASP.NET and can probably be better answered atMicrosoft Official Windows Forms Community Site, I can offer a couple of suggestions:
1. You are loading the datareader and attempting the binding within the Catch block which will only be executed if the opening of the connection throws an exception.
2. Databinding to windows forms controls such as the ComboBox is different than for webcontrols. The datasource must implement the IList interface which the data reader does NOT implement. Therefore, you must databind to a datatable, dataset, dataview, etc. which does implement IList.

Try the following (untested):


Public Sub FillCountryList()
Dim myConn As New OleDBconnection ("Provider=Microsoft.Jet.OLEDB.4.0; data source=C:\postcodedb\postcode.mdb")
Dim SQL As String="SELECT DISTINCT cnt FROM postcode"
Dim dt As New DataTable ("Countries")
Dim da As New OleDbDataAdapter(SQL, DBConnection)
Try
da.Fill(dt)
ComboBox1.DataSource=dt
ComboBox.DisplayMember="cnt"
Catch ex As Exception
MessageBox.Show (ex.ToString)
Finally
dt.Dispose()
da.Dispose()
End Try
End Sub

0 comments:

Post a Comment