1

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.Connection=con; cmd.CommandText = "select * from Table1"; OleDbDataAdapter da = new OleDbDataAdapter(cmd); DataTable dt = new DataTable(); da.Fill(dt); 

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)

2
  • In this way you read ALL of Table1. If you want to read only one record you need to add a WHERE statement to your query. And if there is only one record use an OleDbDataReader instead of filling a DataTable through an adapter Commented Oct 27, 2016 at 17:14
  • @Steve I don't know the command to fill the text box i know it with dataGridView by selecting the row but i don't know how to do it without dataGridView. Commented Oct 27, 2016 at 17:16

1 Answer 1

1

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)) { con.Open(); using(OleDbDataReader reader = cmd.ExecuteReader()) { if(reader.Read()) textBox1.Text = reader["Price"].ToString(); else 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)

Sign up to request clarification or add additional context in comments.

2 Comments

No there isn't any error message i put this thing that you wrote in the form load function but it doesn't put the data in the textbox
It works, i took another look, I made a little mistake from myself the code is ok , thanks man. Accepted the answer

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.