2015-08-03 309 views
1

我一直在嘗試使用textbox的內置屬性進行自動完成。這裏是我的代碼:VB.NET 2013 - 填充:SelectCommand.Connection屬性尚未初始化

Imports System.Data.SqlClient 

Public Class Form1 

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load 
     Dim conn As SqlConnection = New SqlConnection 
     conn.ConnectionString = "Server=PROSOFT-PC\SQLEXPRESS;Database=intellipos;User Id=sa;Password=Password1;" 
     conn.Open() 
     Dim cmd As New SqlCommand 
     cmd.CommandText = "select firstname from customer" 
     Dim ds As New DataSet 
     Me.ds.Clear() 
     Dim da As New SqlDataAdapter(cmd) 
     da.Fill(ds, "list") 
     conn.Close() 
     Dim col As New AutoCompleteStringCollection 
     Dim i As Integer 
     For i = 0 To ds.Tables(0).Rows.Count - 1 
      col.Add(ds.Tables(0).Rows(i)("firstname").ToString()) 
     Next 
     TextBox1.AutoCompleteSource = AutoCompleteSource.CustomSource 
     TextBox1.AutoCompleteCustomSource = col 
     TextBox1.AutoCompleteMode = AutoCompleteMode.Suggest 

    End Sub 
End Class 

但我收到此錯誤:填充:SelectCommand.Connection屬性尚未在ds.fill(da, "list")

被初始化,我只是在VB.NET初學者,原諒我對任何輸入錯誤。

感謝您提前

回答

2

您沒有告訴SqlCommand使用哪個連接。

cmd.Connection = conn 

但是,這只是重複錯誤已經告訴你的東西。

另外,從連接創建Command:

Dim command As SqlCommand = conn.CreateCommand() 
+0

@MarkJasen謝謝先生... – Bhaamb

2

更清晰;

 conn.ConnectionString = "Server=PROSOFT-PC\SQLEXPRESS;Database=intellipos;User Id=sa;Password=Password1;" 
     conn.Open() 
     Dim ds As New DataSet 
     Me.ds.Clear() 
     Dim da As New SqlDataAdapter("select firstname from customer",conn) 
     da.Fill(ds, "list") 
     conn.Close() 

會工作。對於這樣的查詢,您不必聲明command

+0

謝謝您的建議。下一次我會記住這一點 – Bhaamb

相關問題