【问题标题】:C# winforms Argument 1: cannot convert from 'string' to 'int'C# winforms 参数 1:无法从 'string' 转换为 'int'
【发布时间】:2016-11-03 02:45:23
【问题描述】:

我正在尝试将数据读取器中的列读入标签(c#winform) 我的代码如下:

 SqlCommand command1 = new SqlCommand("select  plant_name,plant_id from plant order by plant_id ", connection);

        try
        {
            connection.Open();
            SqlDataReader dr = command1.ExecuteReader();

            while (dr.Read())
            {
                string plantlable = dr.GetInt32("plant_id").ToString();
                labelplantid.Text = plantlable.ToString();

                comboBoxplant.Items.Add(dr["plant_name"]);


            }

            dr.Close();
            dr.Dispose();
            connection.Close();
        }

        catch (Exception ex)
        {

            MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
            Application.Exit();
        }

我在下一行收到错误“Argument 1: cannot convert from 'string' to 'int'”

string plantlable = dr.GetInt32("plant_id").ToString();

带有红色下划线的plant_id。

我做错了什么? 我似乎无法弄清楚。 plant_id 是一个 Int 列类型。 数据库使用 Sql Server 2008。

任何提示将不胜感激。

【问题讨论】:

  • 您试图从非数字字符串中获取整数值,这没有意义。 dr["plant_id"] 应改为使用。有关GetInt32 方法信息,请参阅msdn.microsoft.com/en-us/library/…
  • 谢谢你..这工作..labelplantid.Text= dr["plant_id"].ToString();

标签: c# sql-server ado.net sqldatareader


【解决方案1】:

SqlDataReader.GetInt32 方法将整数作为参数。该整数标记您尝试引用的字段的索引。在您的情况下,“plant_name”将是索引 0,“plant_id”将是索引 1,因为这是您在 SQL 查询中指定的顺序。

您收到错误是因为您没有传递索引,而是将GetInt32 视为字典获取器并尝试直接访问“plant_id”。相反,请尝试以下方法:

string plantlable = dr.GetInt32(1).ToString();

或者,您可以使用索引器(数组)表示法直接从 SqlDataReader 获取值作为对象:

string plantlable = dr["plant_id"].ToString();

【讨论】:

  • 谢谢你..这工作...... string plantlable = dr.GetInt32(1).ToString(); labelplantid.Text = plantlable.ToString();
【解决方案2】:

通过使用这行dr.GetInt32("plant_id"),您正试图从DataReader 中读取一个整数值。并且错误消息说您正在尝试将字符串转换为整数,这意味着 plant_id 列将是 Text 或 Varchar 或类似的东西(不是整数)请您交叉检查类型吗?。

如果是这样,那么您可以尝试SqlDataReader.GetString 方法来读取该值,在这种情况下您无需添加.ToString(),编码将为:

  labelplantid.Text = dr.GetString("plant_id");

【讨论】:

  • 我查看了表格,这里是创建语句.. 很确定 plant_id 是 int CREATE TABLE [dbo].[plant]( [ID] [int] NOT NULL, [plant_id] [int] 非空,[植物名称] [varchar](25) 非空,约束 [PK_plant] 主键集群
  • BTW.. 使用您提供的代码仍然会导致相同的错误:/
【解决方案3】:

对于那些正在寻找答案的人......这里是:

labelplantid.Text= dr["plant_id"].ToString();

或者这个

string plantlable = dr.GetInt32(1).ToString();
labelplantid.Text = plantlable.ToString();

任何一个都有效。感谢您的及时答复:)

【讨论】:

    猜你喜欢
    • 2014-04-02
    • 1970-01-01
    • 1970-01-01
    • 2015-06-12
    • 2018-11-25
    • 1970-01-01
    • 2015-03-09
    • 1970-01-01
    • 2015-02-28
    相关资源
    最近更新 更多