【问题标题】:SqlDataReader Datatype Conversion ErrorSqlDataReader 数据类型转换错误
【发布时间】:2017-09-17 13:38:38
【问题描述】:

我正在尝试从组合框中的数据库加载项目,但在代码中出现了这个意外错误,似乎没有明显的原因。请帮忙。 错误:参数 1:无法从 'string' 转换为 'int'。 在数据库中,“PortName”的数据类型是 Varchar。

Database Table

void FillCombo()
    {
        SqlConnection conn = new SqlConnection(global::flight_management.Properties.Settings.Default.conn);
        string sql = "SELECT PortName FROM PORTS";
        SqlCommand exesql = new SqlCommand(sql, conn);
        SqlDataReader myReader;
       try
        {
            conn.Open();
            myReader = exesql.ExecuteReader();
            while(myReader.Read())
            {
                string sName = myReader.GetString("PortName");
  // ERORR HERE: Argument 1: Cannot convert from 'string' to 'int'
                ComboFromA.Items.Add("sName");
            }
        }

        catch (Exception ex) {lblError.Text = "Error Loading Airports: "+ ex.Message;}
        finally {conn.Close();}
    }

Argument 1: Cannot convert from 'string' to 'int'

【问题讨论】:

  • 我从您的代码中注意到,其中似乎有不同的职责组合。在一种方法中进行数据访问并不是最佳实践,该方法也在 UI 的组合框中创建项目。它可能只是纯粹的示例代码,但仍然需要考虑:-)

标签: c# types type-conversion sqldatareader datareader


【解决方案1】:

从 SqlDataReader 读取数据时,数据库类型很重要

ColumnType 是字符串 GetString

ColumnType 是 int GetInt32

ColumnType 是 Double GetDouble

你可以用那个作为例子 我认为这是来自SqlDataReader的最佳实践阅读价值

myReader.GetString(myReader.GetOrdinal("PortName"));

并替换

ComboFromA.Items.Add("sName") to ComboFromA.Items.Add(sName);

【讨论】:

    【解决方案2】:

    试试下面的代码

    void FillCombo()
        {
            SqlConnection conn = new SqlConnection(global::flight_management.Properties.Settings.Default.conn);
            string sql = "SELECT PortName FROM PORTS";
            SqlCommand exesql = new SqlCommand(sql, conn);
            SqlDataReader myReader;
           try
            {
                conn.Open();
                myReader = exesql.ExecuteReader();
                while(myReader.Read())
                {
                    string sName = myReader.GetString(0);
      //ust use the index 0 for first attribute in select list 
                    ComboFromA.Items.Add("sName");
                }
            }
    
            catch (Exception ex) {lblError.Text = "Error Loading Airports: "+ ex.Message;}
            finally {conn.Close();}
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-06
      • 1970-01-01
      • 2013-04-24
      • 2011-02-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多