Harry Harry - 5 months ago 33
C# Question

C# winforms Argument 1: cannot convert from 'string' to 'int'

I'm trying to read a column from a data reader into a label (c# winform)
My code is as follows:

SqlCommand command1 = new SqlCommand("select plant_name,plant_id from plant order by plant_id ", connection);

SqlDataReader dr = command1.ExecuteReader();

while (dr.Read())
string plantlable = dr.GetInt32("plant_id").ToString();
labelplantid.Text = plantlable.ToString();




catch (Exception ex)

MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);

I get the error "Argument 1: cannot convert from 'string' to 'int' " on the following line

string plantlable = dr.GetInt32("plant_id").ToString();

with the plant_id underlined in RED.

What am I doing wrong?
I can't seem to figure it out. plant_id is a column type Int.
Using Sql Server 2008 for the database.

Any hints would be appreciated thanks.


The SqlDataReader.GetInt32 method takes an integer as a parameter. That integer marks the index of the field you are trying to reference. In your case, "plant_name" would be index 0 and "plant_id" would be index 1, as that is the order that you specified in the SQL query.

You are getting an error because instead of passing the index, you are treating the SqlDataReader as a dictionary and trying to access "plant_id" directly. Instead, try the following:

string plantlable = dr.GetInt32(1).ToString();