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

前提是你 提交于 2019-12-20 07:39:34

问题


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

In C# I have three text boxes (txtId, txtName, txtPrice) and a button (btnSearch). My question is that, In C# I just type FoodID in (txtId) and then click on button Search It'll display FoodName and Price ( from table access) in txtName and txtPrice by itself. I got the source code from you but it error on (OleDbDataReader dr = cmd.ExecuteReader();) its message is "Data type mismatch in criteria expression" .

Please solve this problem for me. This is the whole source code that I got 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:


I assume FoodID is int. You should remove single quotes in this case

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

Even better - use parameters:

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();
    }
}



回答2:


I think the FoodId is of Integer type in the database but over here in the query you have passed as string so convert the string to integer.

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

There seems to be no problem with this line of code :

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



回答3:


I think the problem is in:

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

You need to use the .Text Propertie of the Textbox

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


来源:https://stackoverflow.com/questions/6475547/getting-data-from-access-into-a-text-box-in-c-sharp-by-clicking-a-button

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!