簡體   English   中英

在 Visual Studio 和 SQL 服務器數據庫中使用 Vb.Net 創建搜索 Function

[英]Creating Search Function using Vb.Net in Visual Studio and SQL Server Database

我正在尋找有關創建 function 以對我在 sql 服務器上的數據庫進行排序的幫助,我可以在其中搜索名稱和部件號。 我將我的數據庫連接到 Visual Studio,但在代碼中連接到數據庫並且能夠在數據網格視圖上生成數據庫時遇到了困難。

有什么幫助,謝謝

您需要實現幾個概念:

  1. 連接到數據庫
  2. 使用必要的WHERE子句設置 SQL 命令
  3. 用結果填充數據表
  4. 將 DataTable 綁定到 DataGridView

這是一個示例,我對代碼進行了大量注釋以解釋發生了什么:

' wrap code in Try/Catch because database operations can fail
Try
    ' create a new instance of the connection object
    Using connection = New SqlConnection("My Connection String Here")

        ' create a new instance of the command object
        Using command = New SqlCommand("Select * From MyTable WHERE Name = @name AND PartNumber = @part", connection)
            ' parameterize the query
            command.Parameters.Add("@name", SqlDbType.VarChar).Value = "my name search"
            command.Parameters.Add("@part", SqlDbType.VarChar).Value = "my part number search"

            ' open the connection
            connection.Open()

            ' create a new instance of the data adapter object
            Using adapter = New SqlDataAdapter(command)
                ' fill a DataTable with the data from the adapter
                Dim table = New DataTable()
                adapter.Fill(table)

                ' bind the DataTable to the DataGridView
                MyDataGridView.DataSource = table
            End Using

            ' close the connection
            connection.Close()
        End Using ' disposal of command
    End Using ' disposal of connection
Catch ex As Exception
    ' display the error
    MessageBox.Show(ex.Message)
End Try

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM