【问题标题】:Getting Data from Access into a text box in C# by clicking a button通过单击按钮将数据从 Access 获取到 C# 中的文本框
【发布时间】: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();

【问题讨论】:

    标签: c# .net database ms-access ado.net


    【解决方案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 + "' ";
      

      【讨论】:

        猜你喜欢
        • 2017-09-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多