首先,請不要連接您的SQL中的WHERE參數。使用參數。其次,在您的模塊的頂部添加一個「使用System.Data.OleDb」語句,所以您不必型喜歡的東西:
System.Data.OleDb.OleDbDataAdapter
一遍又一遍。
試試下面的代碼。就個人而言,當我不得不使用數據表等時,我更願意避免所有的DataAdapter廢話,並儘可能保持簡單。
注意,在下面的代碼:
「使用」 的塊。這些將他們內部創建的變量放在他們自己的範圍內,併爲您處理和處理等。
我來代替串接的標準一個OLEDB參數。這是一種更安全的方式來做事,並且創建更清晰,更易讀的代碼,特別是在WHERE子句中有多個條件的情況下。
我假設你的用戶名輸入是一個字符串,因爲你抓住從文本框中的值。如果它實際上是一個int值(例如MS Access中的自動遞增id),則需要改爲使用int數據類型。你可能不得不惹一點麻煩。當你還在搞這個東西時,可能會有點痛苦。但是,使用參數可以提高安全性和可維護性。
一旦您從MyUsers方法獲得了返回的數據表,您應該能夠簡單地設置Gridview的數據源。如果仍然有困難,請按照Steve的建議在設計器中檢查Autogenerate columns屬性,或者將其設置爲代碼。
- 不是我已經將連接字符串移動到項目屬性/設置。您應該在解決方案設計人員中找到這個。將連接字符串放在一處,然後從代碼中的任何位置獲取它。如果您稍後更改連接字符串(例如將您的Db移動到另一臺計算機,服務器共享等),則只需在一個位置進行更改即可。
示例代碼:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.OleDb; // put this here, and stop writing long namespaces inline
namespace WindowsFormsApplication3
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
// Where possible, move code out of specific event handlers
// into methods which can be re-used from other client code.
// Here, I pulled the actual data access out into separate methods,
// and simply call it from the event handler:
this.LoadGridView(textBox1.Text);
}
private void LoadGridView(string UserID)
{
// Now we can load the gridview from other places in our
// code if needed:
this.dataGridView1.DataSource = this.MyUsers(UserID);
}
private DataTable MyUsers(string UserID)
{
var dt = new DataTable();
// Use a SQL Paramenter instead of concatenating criteria:
string SQL = "SELECT * FROM Leave WHERE userid = @UserID";
// The "using" statement limits the scope of the connection and command variables, and handles disposal
// of resources. Also note, the connection string is obtained from the project properties file:
using(OleDbConnection cn = new OleDbConnection(Properties.Settings.Default.MyConnectionString))
{
using (var cmd = new OleDbCommand(SQL, cn))
{
// For simpler things, you can use the "AddWithValue" method to initialize a new parameter,
// add it to the Parameters collection of the OleDBCommand object, and set the value:
cmd.Parameters.AddWithValue("@UserID", UserID);
// Get in, get out, get done:
cn.Open();
dt.Load(cmd.ExecuteReader());
cn.Close();
}
}
return dt;
}
}
}
希望有所幫助。並不是每個人都可以這樣做,但是我發現當你必須使用MS Access時,它提供了最大的靈活性。
winforms或asp.net? – codingbiz