0

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'

1
  • I've noticed from your code there appears to have a distinct mix of responsibilities in it. It is not best practice to have data access in a method which also is creating the items in a combobox for the UI. It maybe just pure example code, but still, something to think about :-) Commented Sep 17, 2017 at 13:50

2 Answers 2

2

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);
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.