N
NH
Hi, I am building a windows forms app (vb.net, .net 2.0).
For basic loading of a combo box which of the two options below is best
practice or more efficient. The main difference is should you use a
datareader and load the results into a table or use a sqldataAdapter and fill
a dataTable?
OPTION 1:
Public Function GetData(ByVal commandText As String, ByVal connectionString
As String, ByVal commandType As CommandType) As DataTable
Using connection As New SqlConnection(connectionString)
connection.Open()
Using command As New SqlCommand(commandText, connection)
command.CommandType = commandType
Using reader As SqlDataReader = command.ExecuteReader()
Dim table As New DataTable
table.Load(reader)
Return table
End Using
End Using
End Using
End Function
Usage:
Me.ListBox1.DataSource = GetData("Select UnitID,Name from Unit", "connection
string", CommandType.Text)
Me.ListBox1.DisplayMember = "Name"
Me.ListBox1.ValueMember = "UnitID"
OPTION 2:
Dim myCmd1 As SqlCommand = myconn.CreateCommand
myCmd1.CommandText = "Select UnitID,Name from Unit"
myCmd1.Connection = myconn
Dim da As New SqlDataAdapter()
da.SelectCommand = myCmd1
Dim dt As New DataTable()
da.Fill(dt)
Me.cmbUnitID.DisplayMember = "Name"
Me.cmbUnitID.ValueMember = "UnitID"
Me.cmbUnitID.DataSource = dt
For basic loading of a combo box which of the two options below is best
practice or more efficient. The main difference is should you use a
datareader and load the results into a table or use a sqldataAdapter and fill
a dataTable?
OPTION 1:
Public Function GetData(ByVal commandText As String, ByVal connectionString
As String, ByVal commandType As CommandType) As DataTable
Using connection As New SqlConnection(connectionString)
connection.Open()
Using command As New SqlCommand(commandText, connection)
command.CommandType = commandType
Using reader As SqlDataReader = command.ExecuteReader()
Dim table As New DataTable
table.Load(reader)
Return table
End Using
End Using
End Using
End Function
Usage:
Me.ListBox1.DataSource = GetData("Select UnitID,Name from Unit", "connection
string", CommandType.Text)
Me.ListBox1.DisplayMember = "Name"
Me.ListBox1.ValueMember = "UnitID"
OPTION 2:
Dim myCmd1 As SqlCommand = myconn.CreateCommand
myCmd1.CommandText = "Select UnitID,Name from Unit"
myCmd1.Connection = myconn
Dim da As New SqlDataAdapter()
da.SelectCommand = myCmd1
Dim dt As New DataTable()
da.Fill(dt)
Me.cmbUnitID.DisplayMember = "Name"
Me.cmbUnitID.ValueMember = "UnitID"
Me.cmbUnitID.DataSource = dt