簡體   English   中英

如何使用選擇查詢中的數據集填充datagridview?

[英]How to populate datagridview with dataset from select query?

我正在使用SELECT查詢創建搜索欄,並且要將結果傳輸到DataGridView。 但是我總是得到一個空的DataGridView。

查詢沒有問題,我已經嘗試在訪問中手動輸入它。 我在代碼中做錯了什么? 這里是:

Using conn = New OleDbConnection(connstring)
    Try
        Dim Sql As String = "SELECT * FROM Products WHERE [Product Name] LIKE '" & txtSearchProduct.Text & "*'"

        Dim da As New OleDbDataAdapter(Sql, conn)
        Dim ds As New DataSet
        da.Fill(ds)
        DataGridView2.DataSource = ds.Tables(0)

    Catch ex As Exception
            MsgBox(ex.ToString, MsgBoxStyle.OkOnly Or MsgBoxStyle.Exclamation, "Error")
    End Try
End Using

正如我在評論中所述。 ADO.Net使用%等來保持與大多數主要Sql引擎的一致性。 但是我想指出,您的查詢是不安全的,並且會受到SQL注入的影響,因此我提供了一個示例代碼,其中使用參數將用戶輸入傳遞給命令。

還要注意,可以像Using OleDbConnection一樣,在Using語句中聲明OleDbDataAdapter但是請注意,如果您打算對數據集(ds)進行其他操作,則可能必須擴大其范圍。

Using conn As OleDbConnection = New OleDbConnection(connstring)
    Try
        Dim Sql As String = "SELECT * FROM Products WHERE [Product Name] LIKE @Product"

        Using da As OleDbDataAdapter = New OleDbDataAdapter(Sql, conn)
            da.SelectCommand.Parameters.Add("@Product", OleDbType.Varchar).Value = txtSearchProduct.Text & "%"
            Dim ds As New DataSet
            da.Fill(ds)
            DataGridView2.DataSource = ds.Tables(0)
        End Using
    Catch ex As Exception
        MsgBox(ex.ToString, MsgBoxStyle.OkOnly Or MsgBoxStyle.Exclamation, "Error")
    End Try
End Using

就像Charles提到的,使用參數總是更好。 我的答案有點不同,它使用的是讀取器而不是適配器,以及數據表而不是整個數據集。 僅當您打算寫回表或典型情況包括綁定過程時,才應使用適配器。 當您有多個表並且需要關聯它們時,通常使用DataSet。 另請注意,無論您在搜索列中的位置如何匹配字符串,都很可能需要在參數中使用前一個%。

    Try
        Using conn = New OleDbConnection("YourConnString")
            conn.Open()

            Dim Cmd As New OleDbCommand("SELECT * FROM Products WHERE [Product Name] LIKE @Product", conn)
            Cmd.Parameters.AddWithValue("@Product", "'%" & txtSearchProduct.Text & "%'")
            Dim ProductsRDR As OleDbDataReader = Cmd.ExecuteReader

            Dim DTable As New DataTable With {.TableName = "Products"}
            DTable.Load(ProductsRDR)

            DataGridView1.DataSource = DTable


            conn.Close()
        End Using
    Catch ex As Exception
        MsgBox(ex.ToString, MsgBoxStyle.OkOnly Or MsgBoxStyle.Exclamation, "Error")
    End Try

您要做的就是用Sql字符串中的%替換*符號,如下所示:

這是您錯誤的Sql字符串:

Dim Sql As String = "SELECT * FROM Products WHERE [Product Name] LIKE '" & txtSearchProduct.Text & "*'"

更改為此:

Dim Sql As String = "SELECT * FROM Products WHERE [Product Name] LIKE '" & txtSearchProduct.Text & "%'"

在此處輸入圖片說明

這應該涵蓋那里的大多數常見方案。

Imports System.Data.SqlClient
Public Class Form1
    Dim sCommand As SqlCommand
    Dim sAdapter As SqlDataAdapter
    Dim sBuilder As SqlCommandBuilder
    Dim sDs As DataSet
    Dim sTable As DataTable

    Private Sub load_btn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles load_btn.Click
        Dim connectionString As String = "Data Source=.;Initial Catalog=pubs;Integrated Security=True"
        Dim sql As String = "SELECT * FROM Stores"
        Dim connection As New SqlConnection(connectionString)
        connection.Open()
        sCommand = New SqlCommand(sql, connection)
        sAdapter = New SqlDataAdapter(sCommand)
        sBuilder = New SqlCommandBuilder(sAdapter)
        sDs = New DataSet()
        sAdapter.Fill(sDs, "Stores")
        sTable = sDs.Tables("Stores")
        connection.Close()
        DataGridView1.DataSource = sDs.Tables("Stores")
        DataGridView1.ReadOnly = True
        save_btn.Enabled = False
        DataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect

    End Sub

    Private Sub new_btn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles new_btn.Click
        DataGridView1.[ReadOnly] = False
        save_btn.Enabled = True
        new_btn.Enabled = False
        delete_btn.Enabled = False
    End Sub

    Private Sub delete_btn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles delete_btn.Click
        If MessageBox.Show("Do you want to delete this row ?", "Delete", MessageBoxButtons.YesNo) = DialogResult.Yes Then
            DataGridView1.Rows.RemoveAt(DataGridView1.SelectedRows(0).Index)
            sAdapter.Update(sTable)
        End If
    End Sub

    Private Sub save_btn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles save_btn.Click
        sAdapter.Update(sTable)
        DataGridView1.[ReadOnly] = True
        save_btn.Enabled = False
        new_btn.Enabled = True
        delete_btn.Enabled = True
    End Sub
End Class

暫無
暫無

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

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