[c#] Reading int values from SqlDataReader

hi can anyone please help me with this fetching from database of int values im having difficulty in fetching int values , it works for varchar but not int can someone help me out please

if (int.TryParse(TxtFarmerCode.Text, out intValue))
{
   using (SqlConnection sqlConn = new SqlConnection("Data Source=TANYA-PC;Initial Catalog=biore1;Integrated Security=True")) //here goes connStrng or the variable of it
   {
      sqlConn.Open();
      string sqlQuery = @"SELECT farmername,villagename,gender,farmsize FROM cottonpurchase WHERE farmercode = @code";

      using (SqlCommand cmd = new SqlCommand(sqlQuery, sqlConn))
      {
         cmd.Parameters.Add("@code", SqlDbType.Int).Value = intValue;
         using (SqlDataReader reader = cmd.ExecuteReader())
         {;
            if (reader.Read())
            {
               TxtFarmerName.Text = (string)reader[0];
               TxtVillageName.Text = (string)reader[1];
               TxtGender.Text = (string)reader[2];
            }
            else
               MessageBox.Show("For Farmer Code " + intValue.ToString() + " there is no farmer in the database.");
         }
      }
   }
}

i want to fetch txtfarmersize which is int but dont know how to do it please help me?

This question is related to c# ado.net

The answer is


Use the GetInt method.

reader.GetInt32(3);

based on Sam Holder's answer, you could make an extension method for that

namespace adonet.extensions
{
  public static class AdonetExt
  {
    public static int GetInt32(this SqlDataReader reader, string columnName)
    {
      return reader.GetInt32(reader.GetOrdinal(columnName));
    }
  }
}

and use it like this

using adonet.extensions;

//...

int farmsize = reader.GetInt32("farmsize");

assuming there is no GetInt32(string) already in SqlDataReader - if there is any, just use some other method name instead


you can use

reader.GetInt32(3);

to read an 32 bit int from the data reader.

If you know the type of your data I think its better to read using the Get* methods which are strongly typed rather than just reading an object and casting.

Have you considered using

reader.GetInt32(reader.GetOrdinal(columnName)) 

rather than accessing by position. This makes your code less brittle and will not break if you change the query to add new columns before the existing ones. If you are going to do this in a loop, cache the ordinal first.


This should work:

txtfarmersize = Convert.ToInt32(reader["farmsize"]);

Call ToString() instead of casting the reader result.

reader[0].ToString();
reader[1].ToString();
// etc...

And if you want to fetch specific data type values (int in your case) try the following:

reader.GetInt32(index);

TxtFarmerSize.Text = (int)reader[3];