我正在制作一个用户可以查看其产品订单的程序。他们的产品订单存储在名为“tblOrders”的Access数据库表中。 “tblOrders”字段是ProductName,Quantity,PriceEach,TotalPricePerLine,OrderTotalPrice和Username。
我希望用户只能看到他们的订单,而不是整个表。为此,我希望显示的订单基于用户的用户名。
到目前为止,这是我的代码:
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
然而,这并不完全符合我的要求。它将WHOLE表显示在DataGridView中。我希望它基于用户的用户名。
非常感谢任何帮助和建议。
答案 0 :(得分:0)
您的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