Getting data from Access into a text box in C # by clicking a button

I have a table in MS Access that contains: (FoodID, FoodName, Price).

In C #, I have three text fields (txtId, txtName, txtPrice) and a button (btnSearch). My question is that in C # I just type FoodID in (txtId) and then click the Search button. It maps the name FoodName and Price (from accessing the table) to txtName and txtPrice on its own. I received the source code from you, but he made a mistake (OleDbDataReader dr = cmd.ExecuteReader ();) his message "Data type mismatch in the criteria expression".

Please solve this problem for me. This is all the source code I received for you.

System.Data.OleDb.OleDbConnection conn = new OleDbConnection();
conn.ConnectionString = "your connection string";
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = conn;
cmd.CommandText = "select FoodName, Price from tablename where FoodID = '" + txtId + "' ";
conn.Open();
OleDbDataReader dr = cmd.ExecuteReader();//error this line!
while(dr.Read())
{
     txtName.Text = dr["FoodName"].ToString();
     txtPrice.Text = dr["Price"].ToString(); 
}
dr.Close();
conn.Close();
-1
3

, FoodID - int.

cmd.CommandText = " FoodName, tablename, FoodID =" + txtId;

- :

using (var connection = new OleDbConnection("your connection string"))
using (var command = connection.CreateCommand())
{
    command.CommandText = "select FoodName, Price from tablename where FoodID = @FoodID";
    command.Parameters.AddWithValue("FoodID", int.Parse(txtId.Text));
    connection.Open();
    var reader = command.ExecuteReader();
    while (reader.Read())
    {
        txtName.Text = reader["FoodName"].ToString();
        txtPrice.Text = reader["Price"].ToString();
    }
}
+4

, FoodId Integer , , , , .

cmd.CommandText = "select FoodName, Price from tablename where FoodID = '" + int.Parse(txtId.Text) + "' " ;

, :

OleDbDataReader dr = cmd.ExecuteReader();// correct way
0

, :

cmd.CommandText = "select FoodName, Price from tablename where FoodID = '" + txtId + "' ";

.Text Propertie

cmd.CommandText = "select FoodName, Price from tablename where FoodID = '" + txtId.Text + "' ";
0

All Articles