[英]How to insert a table from an MS Access database based on the username into a DataGridView?
我正在制作一個程序,用戶可以在其中查看其產品訂單。 他們的產品訂單存儲在一個名為“ tblOrders”的Access數據庫表中。 “ tblOrders”字段是ProductName,Quantity,PriceEach,TotalPricePerLine,OrderTotalPrice和用戶名。
我希望用戶只看到他們的訂單,而不是整個表。 為此,我希望顯示的訂單基於用戶的用戶名。
到目前為止,這是我的代碼:
Imports System.Data.OleDb
Public Class Form1
provider = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source ="
dataFile = Application.StartupPath & "\SAC1 Database.mdb"
connString = provider & dataFile
Dim MyConn As OleDbConnection
Dim da As OleDbDataAdapter
Dim ds As DataSet
Dim tables As DataTableCollection
Dim source1 As New BindingSource
Private Sub btnDisplayDataGrid_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDisplayDataGrid.Click
MyConn = New OleDbConnection
MyConn.ConnectionString = connString
ds = New DataSet
tables = ds.Tables
da = New OleDbDataAdapter("Select * from [tblOrders]", MyConn)
da.Fill(ds, "items")
Dim view As New DataView(tables(0))
source1.DataSource = view
DataGridOrders.DataSource = view
End Sub
但是,這並不能完全滿足我的要求。 它將整個表顯示到DataGridView中。 我希望它基於用戶的用戶名。
任何幫助和建議,將不勝感激。
您的sql應按用戶名過濾。 ? 是由參數值替換的占位符:根據需要更改GetMyUserName函數以獲取應用程序所需的用戶名
OleDbDataAdapter生成一些額外的命令,這些命令對於插入,刪除,更新操作是不需要的。 如果您只需要讀取數據,則OleDbCommand最適合您的需求
Private Sub btnDisplayDataGrid_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDisplayDataGrid.Click
Dim dt As New DataTable
Dim username As string = GetMyUserName()
Dim cmd As New OleDbCommand("Select * from [tblOrders] where username = ?", MyConn)
cmd.Parameters.AddWithValue("username", username)
Dim reader As OleDbDataReader = cmd.ExecuteReader()
dt.Load(reader)
source1.DataSource = dt
DataGridOrders.DataSource = dt
End Sub
Private Function GetMyUserName() As string
GetMyUserName = "myname"
End Function
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.