Rjey Rjey - 7 months ago 46
C# Question

Want to Fill Text Box With Access Data

In C# I want to use access data to fill my textBox I Am using ADO.Net To connect to access.So far I've got this:

OleDbConnection con = new OleDbConnection(Price.constr);
OleDbCommand cmd = new OleDbCommand();
cmd.CommandText = "select * from Table1";
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
DataTable dt = new DataTable();

Price.constr is my connection String.
I want to fill textBox1 with the data in the Price Column Where my row ID = 1.(For Example)


If you want to read only one record from your table then there is no need to return the whole table and use an adapter to fill a datatable. You can simply ask the database to return just the record you are interested in.

string cmdText = "select * from Table1 WHERE ID = 1";
using(OleDbConnection con = new OleDbConnection(Price.constr))
using(OleDbCommand cmd = new OleDbCommand(cmdText, con))
    using(OleDbDataReader reader = cmd.ExecuteReader())
           textBox1.Text = reader["Price"].ToString();
           textBox1.Text = "No record found";

I have enclose the connection, command and reader in an using statement because these are disposable objects and it is a good practice to destroy them when you have finished to use them. (In particular the connection could cause problems if you don't dispose it)

Notice also that I have used the constant 1 to retrieve the record. I bet that you want this to be dynamic and in this case I suggest you to look at how to PARAMETRIZE your queries. (Don't do string concatenations)