我尝试从MS-Access表中获取一个数据列,并将其显示在像这样的TextBox中
public partial class Form1 : Form
{
public OleDbConnection database;
public Form1()
{
InitializeComponent();
}
private OleDbConnection Database_Connection;
private void Open_Database_button_Click(object sender, EventArgs e)
{
Database_Connection = new OleDbConnection(
"Provider=Microsoft.Jet.OLEDB.4.0;Data Source="test.mdb");
OleDbCommand Command = new OleDbCommand(
" SELECT top 1 * from test", Database_Connection);
Database_Connection.Open();
OleDbDataReader DB_Reader = Command.ExecuteReader();
// How can I display the column in TextBox?
}
...
}
答案 0 :(得分:3)
尝试以这种方式更改Open_Database_button_Click:
private void Open_Database_button_Click(object sender, EventArgs e)
{
using(OleDbConnection con = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=test.mdb" ))
using(OleDbCommand Command = new OleDbCommand(" SELECT top 1 * from test", con))
{
con.Open();
OleDbDataReader DB_Reader = Command.ExecuteReader();
if(DB_Reader.HasRows)
{
DB_Reader.Read();
textbox1.Text = DB_Reader.GetString("your_column_name");
}
}
}
我已更改/添加的内容:
using
添加到Disposable对象,因此它们会自动生成
不再需要时关闭