codice:
Private StringaConnessione As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\dati\test\test.mdb"
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
'acquisisco i dati di tabella1 in datatable
Dim dt As DataTable = GetDataTable(StringaConnessione, "select * from tabella1")
'se non contiene righe, esco
If dt.Rows.Count = 0 Then Return
'metto in TextBox il campo nome della prima riga
'se è vuoto, ossia se è DbNull.Value, metto la stringa vuota
Me.TextBox1.Text = NullToString(dt.Rows(0)("nome"))
End Sub
'metti un metodo statico RIUSABILE che ti restituisce un datatable
'-------------------------------------------------------------------------------------
'Restituisce un oggetto DataTable o lancia eccezione in caso di errore
'parametri: Stringa di connessione, stringa sql
'-------------------------------------------------------------------------------------
Public Function GetDataTable(ByVal stringaConnessione As String, ByVal stringaSQL As String) As DataTable
Try
'creo un nuovo DataAdapter
Dim DataAdapter As New OleDbDataAdapter(stringaSQL, stringaConnessione)
'creo un DataTable e lo riempio con i dati
Dim DataTable As New DataTable
'DataAdapter.FillSchema(DataTable, SchemaType.Source)
DataAdapter.Fill(DataTable)
Return DataTable
Catch ex As System.Data.ConstraintException
Try
'creo un nuovo DataAdapter e provo senza caricare lo schema
Dim DataAdapter As New OleDbDataAdapter(stringaSQL, stringaConnessione)
'creo un DataTable e lo riempio con i dati
Dim DataTable As New DataTable
DataAdapter.Fill(DataTable)
Return DataTable
Catch ex1 As Exception
Throw
End Try
Catch Errore As Exception
Throw
End Try
End Function
'un campo di tabella può restituire un valore null
'in questo caso mi deve restituire una stringa vuota
'--------------------------------------------------------------
'Converte DBNull nella stringa vuota ""
'--------------------------------------------------------------
Public Function NullToString(ByVal v As Object) As String
If IsDBNull(v) Then
Return ""
Else
Return CType(v, String)
End If
End Function
Quersto è un modo che fa uso del DataTable.
Un altro contempla l'uso del DataReader