从访问到在C#中的文本框获取的数据通过点击按钮 [英] Getting Data from Access into a text box in C# by clicking a button
问题描述
我在MS Access表包含:(FoodID,FoodName,价格)。
在C#中我有三个文本框(txtId,txtName的,txtPrice)和一个按钮(btnSearch)。 我的问题是,在C#中我只需要输入FoodID在(txtId),然后点击搜索按钮,它会显示FoodName和价格(从表中访问)在改为txtName和txtPrice本身。我得到的源$ C $ C从你,但它的误差(OleDbDataReader博士= cmd.ExecuteReader())。它的消息是在标准前pression数据类型不匹配
请解决这个问题对我来说。这是我对你的整个源$ C $ C。
System.Data.OleDb.OleDbConnection康恩=新的OleDbConnection();
conn.ConnectionString =您的连接字符串;
OleDbCommand的CMD =新的OleDbCommand();
cmd.Connection =康涅狄格州;
cmd.CommandText =选择FoodName,价格表名,其中FoodID ='+ txtId +';
conn.Open();
OleDbDataReader博士= cmd.ExecuteReader(); //错误这一行!
而(dr.Read())
{
txtName.Text =博士[FoodName]的ToString()。
txtPrice.Text =博士[价格]的ToString()。
}
dr.Close();
conn.Close();
我假设 FoodID
为int。您应该删除单引号在这种情况下
cmd.CommandText =选择FoodName,价格表名,其中FoodID =+ txtId;
更妙的是 - 使用参数:
使用(VAR连接=新的OleDbConnection(您的连接字符串))
使用(VAR命令= connection.CreateCommand())
{
command.CommandText =选择FoodName,价格表名,其中FoodID = @FoodID;
command.Parameters.AddWithValue(FoodID,int.Parse(txtId.Text));
connection.Open();
变种读者= Command.ExecuteReader却();
而(reader.Read())
{
txtName.Text =读卡器[FoodName]的ToString()。
txtPrice.Text =读卡器[价格]的ToString()。
}
}
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();
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();
}
}
这篇关于从访问到在C#中的文本框获取的数据通过点击按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!