SqlDataReader Datatype Conversion Error

1.4k Views Asked by At

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'

2

There are 2 best solutions below

0
On BEST ANSWER

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);
0
On

try the following code

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();}
    }