Reputation: 11265
I try to get one data column from a MS-Access table and display it in a TextBox like this
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?
}
...
}
Upvotes: 0
Views: 10095
Reputation: 216243
Try to change your Open_Database_button_Click in this way:
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");
}
}
}
What I have changed/added:
using
to the Disposable objects, so they will automatically
closed when no more neededUpvotes: 3