Reputation: 2941
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.
Upvotes: 0
Views: 1633
Reputation: 24726
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();
Upvotes: 2
Reputation: 2941
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 :)
Upvotes: 0
Reputation: 29036
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");
Upvotes: 0