简体   繁体   中英

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

        try
        {
            connection.Open();
            SqlDataReader dr = command1.ExecuteReader();

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

                comboBoxplant.Items.Add(dr["plant_name"]);


            }

            dr.Close();
            dr.Dispose();
            connection.Close();
        }

        catch (Exception ex)
        {

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

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 GetInt32 as a dictionary getter and trying to access "plant_id" directly. Instead, try the following:

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

Alternatively, you can get the value directly as an object from the SqlDataReader using indexer (array) notation:

string plantlable = dr["plant_id"].ToString();

By using this Line dr.GetInt32("plant_id") you are trying to read an integer value from the DataReader. and the Error message says that you are trying to convert a string to an Integer, which means that the plant_id column will be either a Text or a Varchar or something similar(not an integer) Could you please crosscheck the type?.

If so then you can try SqlDataReader.GetString method to read that value, in this case you need not to add .ToString() , th ecode will be :

  labelplantid.Text = dr.GetString("plant_id");

For those looking for the answer.. here it is:

labelplantid.Text= dr["plant_id"].ToString();

or this

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

either one works. Thanks for the prompt answers :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM