Dim objConn As New System.Data.SqlClient.SqlConnection
Dim objCmd As New System.Data.SqlClient.SqlCommand
Dim dtAdapter As New System.Data.SqlClient.SqlDataAdapter
Dim ds As New DataSet
Dim dt As DataTable
Dim strConnString,strSQL As String
strConnString = "Server=localhost;UID=sa;PASSWORD=;database=mydatabase;Max Pool Size=400;Connect Timeout=600;"
strSQL = "SELECT * FROM product"
objConn.ConnectionString = strConnString
With objCmd
.Connection = objConn
.CommandText = strSQL
.CommandType = CommandType.Text
End With
dtAdapter.SelectCommand = objCmd
dtAdapter.Fill(ds)
dt = ds.Tables(0)
dtAdapter = Nothing
objConn.Close()
objConn = Nothing
ComboBox1.DataSource = dt
ComboBox1.DisplayMember = "TypeProductName"
ComboBox1.ValueMember = "TypeProductID"
อืมม เราลองไปเขียนดูเล่นๆ มันก็ออกนะคะ แต่เครื่องนี้ไม่มี sql server เลยสร้าง Access ขึ้นมาทดลอง ดัดแปลงโค้ดนิดๆหน่อยๆน่ะค่ะ
แบบนี้ Code (VB.NET)
Imports System.Data
Imports System.Data.OleDb
Public Class Form1
Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim objConn As New OleDbConnection
Dim objCmd As OleDbCommand
Dim dtAdapter As New OleDbDataAdapter
Dim ds As New DataSet
Dim dt As DataTable
Dim strConnString, strSQL As String
strConnString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\Mydata.accdb"
'objConn = New OleDbConnection(strConnString)
objConn.ConnectionString = strConnString
objConn.Open()
strSQL = "SELECT * FROM product"
objCmd = New OleDbCommand
With objCmd
.Connection = objConn
.CommandText = strSQL
.CommandType = CommandType.Text
End With
dtAdapter.SelectCommand = objCmd
dtAdapter.Fill(ds)
dt = ds.Tables(0)
dtAdapter = Nothing
objConn.Close()
objConn = Nothing
ComboBox1.DataSource = dt
ComboBox1.DisplayMember = "TypeProductName"
ComboBox1.ValueMember = "TypeProductID"
End Sub
End Class
ลองตรวจสอบ โค้ดดูอีกทีนะคะ สู้ๆ
Date :
2012-05-08 13:04:48
By :
mayapopy
No. 7
Guest
Code (VB.NET)
Imports System.Data.SqlClient
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim myCNN As New SqlClient.SqlConnection("Data Source=Your Server;Initial Catalog=Your DB;Persist Security Info=True;User ID=Username;Password=Your Password")
If myCNN.State = ConnectionState.Open Then myCNN.Close()
myCNN.Open()
Dim sqlserch As String = "SELECT * from Product"
myADP = New SqlDataAdapter(sqlserch, myCNN)
myADP.Fill(ds, "Product")
If ds.Tables("Product").rows.count <> 0 then
Dim Drow As DataRow
For Each Drow In ds.Tables("Product").Rows
ComboBox1.item.add(Drow("TypeProductID"))
ComboBox2.item.add(Drow("TypeProductName "))
Next
End if
End Sub