通过单击按钮将数据从Access获取到C#中的文本框

我在MS Access中有一个表包含:(FoodID,FoodName,Price)。

在C#中,我有三个文本框(txtId,txtName,txtPrice)和一个按钮(btnSearch)。 我的问题是,在C#中我只需输入(txtId)中的FoodID然后点击按钮搜索它将自动显示txtName和txtPrice中的FoodName和Price(来自表访问)。 我从你那里得到了源代码,但是它的错误(OleDbDataReader dr = cmd.ExecuteReader();)它的消息是“条件表达式中的数据类型不匹配”。

请帮我解决这个问题。 这是我为您提供的完整源代码。

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

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

我认为FoodId在数据库中是Integer类型,但是在你已经作为字符串传递的查询中,所以将字符串转换为整数。

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

这行代码似乎没有问题:

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

我认为问题在于:

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

您需要使用文本框的.Text属性

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