まず、SQLでWHEREパラメータを連結しないでください。パラメータを使用します。次に、モジュールの先頭に「using System.Data.OleDb」ステートメントを追加して、次のように入力する必要がないようにします。
System.Data.OleDb.OleDbDataAdapter
何度も何度も。
次のコードを試してください。個人的には、データテーブルなどを操作する必要がある場合は、DataAdapterの意味をすべて避け、できるだけシンプルに保つことを好みます。
以下のコードに注意してください。
「使用中」のブロック。これらは、それらの中で作成された変数を独自のスコープ内に配置し、廃棄などを処理します。
基準を連結する代わりに、OleDbパラメーターを使用しました。これは物事を行うためのはるかに安全な方法であり、特にWHERE句にいくつかの基準がある場合は、はるかにクリーンで読みやすいコードも作成します。
テキストボックスから値を取得しているため、UserID入力は文字列であると想定しています。それが実際にint値(MS Accessの自動インクリメントIDなど)である場合は、代わりにintデータ型を使用する必要があります。あなたはそれを少しいじる必要があるかもしれません。あなたがまだこのことを理解しているとき、それは少し苦痛かもしれません。ただし、パラメータを使用すると、セキュリティと保守性が向上します。
MyUsersメソッドからの戻り値としてデータテーブルを取得すると、Gridviewのデータソースを簡単に設定できるようになります。それでも問題が解決しない場合は、Steveの提案に従って実行し、デザイナーで[列の自動生成]プロパティを確認するか、コードで設定します。
- 接続文字列をプロジェクトのプロパティ/設定に移動したわけではありません。これは、ソリューションデザイナで見つける必要があります。接続文字列を1つの場所に配置すると、コード内のどこからでも接続文字列を取得できます。後で接続文字列を変更する場合(Dbを別のコンピューター、サーバー共有などに移動する場合など)、1か所で変更するだけで済みます。
サンプルコード:
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;
}
}
}
お役に立てば幸いです。それは誰もがそれを行う方法ではありませんが、MSAccessを使用する必要がある場合に最大限の柔軟性を提供することがわかりました。