Search code examples
c#typestype-conversionsqldatareaderdatareader

SqlDataReader Datatype Conversion Error


I am trying to load items from database in combobox but in code this unexpected error came and there seems to be no apparent reason. Please help. Error: Argument 1: Cannot convert from 'string' to 'int'. In database, the datatype of 'PortName' is 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'


Solution

  • Database types are important when reading data from SqlDataReader

    ColumnType is String GetString

    ColumnType is int GetInt32

    ColumnType is Double GetDouble

    you can use the one as the example I think this is the Best practice read value from SqlDataReader

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

    And replace

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