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

Posted

技术标签:

【中文标题】通过单击按钮将数据从 Access 获取到 C# 中的文本框【英文标题】:Getting Data from Access into a text box in C# by clicking a button 【发布时间】:2011-06-25 03:08:46 【问题描述】:

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

在 C# 中,我有三个文本框(txtId、txtName、txtPrice)和一个按钮(btnSearch)。 我的问题是,在 C# 中,我只需在 (txtId) 中键入 FoodID,然后单击按钮 Search 它会在 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();

【问题讨论】:

【参考方案1】:

我假设FoodID 是整数。在这种情况下,您应该删除单引号

cmd.CommandText = "select FoodName, Price from tablename where 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();
    

【讨论】:

@Sophorn - 如果有效,请标记答案。如果它不起作用,请说明问题。 您提供的解决方案正是我想要的。谢谢。【参考方案2】:

我认为 FoodId 在数据库中是 Integer 类型,但在查询中您已将其作为字符串传递,因此将字符串转换为整数。

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

这行代码好像没有问题:

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

【讨论】:

【参考方案3】:

我认为问题出在:

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

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

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

【讨论】:

以上是关于通过单击按钮将数据从 Access 获取到 C# 中的文本框的主要内容,如果未能解决你的问题,请参考以下文章

如何通过按钮单击将数据导出到 linq c# 中的 .csv 文件

c# - 从 ms access 数据库中随机生成数据

从 c# windows 应用程序中的按钮单击将值返回到网格

不通过 C# 从 ms access 数据库返回任何数据,如果我在 ms access 上运行相同的查询,它将获取数据

从 ms-access 获取数据到 ms-word

基于单击命令按钮将表从 Access 导出到 Excel