技術分享教學

VB中..使用文字輸入方塊加資料庫完成”自動完成功能”

在藍色小舖找到的解決方法
原PO網址


使用北風資料庫的Customers資料表的Customerid欄位做為
自動完成的欄位,在表單裡放入一個TextBox,程式如下:

    Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        TextBox1.AutoCompleteMode = AutoCompleteMode.SuggestAppend
        TextBox1.AutoCompleteSource = AutoCompleteSource.CustomSource

        Dim cn As New SqlConnection("server=db-machine;database=northwind;user id=sa;password=sa")
        Dim cmd As New SqlCommand("select customerid from customers", cn)

        cn.Open()
        Dim reader As SqlDataReader = cmd.ExecuteReader

        Do While reader.Read
            TextBox1.AutoCompleteCustomSource.Add(reader(0))
        Loop

        reader.Close()
        cmd.Dispose()
    End Sub