Yudish Nundun
Yudish Nundun

Reputation: 23

Having error with C# while connecting to a database

try
{
    connection.Open();
    myReader = cmdDatabase.ExecuteReader();
    while (myReader.Read())
    {
       string nationality = myReader.GetString("country");
       cmbnationality.Items.Add(nationality);
    }
}

I am having this problem:

Error   2   Argument 1: cannot convert from 'string' to 'int'

At the line:

string nationality = myReader.GetString("country");

Can anyone help me? I am basically trying to populate values in a combobox from my database. "country" is my column name in the database.

Upvotes: 0

Views: 80

Answers (4)

Waqar
Waqar

Reputation: 9331

GetString expects an int argument, while you are passing a string. Do this instead:

string nationality = myReader.GetString (myReader.GetOrdinal("country"));

Please read the following for details:

GetOrdinal

GetString

Upvotes: 0

Steve
Steve

Reputation: 216293

The correct way to use GetString is the following

string nationality = myReader.GetString (myReader.GetOrdinal("country"));

MSDN - GetOrdinal
MSDN - GetString

Upvotes: 2

Andy
Andy

Reputation: 8562

GetString takes an int parameter, which is the ordinal of the data you want. Change it to:

string nationality = myReader.GetString(myReader.GetOrdinal("country"));

See the documentation for IDataReader.GetString method here.

Upvotes: 3

phadaphunk
phadaphunk

Reputation: 13303

It's simply because Reader.GetString() expects an int as a parameter. You are passing a string. If you have to pass a string you will have to call it this way :

string nationality = myReader.GetString (reader.GetOrdinal("country"));

Upvotes: 2

Related Questions