37

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?

5
  • Does using (SqlDataReader reader = cmd.ExecuteReader()) {; throw a syntax error? is that ; supposed to be there? Commented Sep 12, 2011 at 13:21
  • txtfarmersize is the name of a field or the ID of a textbox control on your form? Commented Sep 12, 2011 at 13:23
  • 3
    I feel duty-bound to point out that you are accessing a database directly from UI code, which is a terrible way of doing things. The app will freeze while the DB is being accessed, if there's a DB error your whole app will crash, if you modify your DB query there you'll cause errors unless you remember to keep your DataReader indices in sync.. if this app is to be used by anyone can I suggest some background reading into correct app design? Commented Sep 12, 2011 at 13:25
  • @Brad: Just so you know, at least in this example, it would not cause a syntax error. A lone semicolon is just an empty statement. It doesn't really do anything special except for allowing you to use it as a breakpoint. If on the other hand the code was exactly as you have shown without anything else, then that would be a syntax error (unmatched parenthesis). Commented Sep 12, 2011 at 19:42
  • @Jeff ah very interesting. That's a cool tool. Thanks Commented Sep 13, 2011 at 0:10

6 Answers 6

75

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.

Sign up to request clarification or add additional context in comments.

5 Comments

Is there similar way to get string(varchar) ? for example reader.GetVarchar(reader.getOrdinal(columnName))
Just found it. reader.GetString(reader.GetOrdinal(columnName))
@RayLoveless You'll get an exception if the value is null. You can use reader.IsDBNull(reader.GetOrdinal(columnName)) to check for a null value and act appropriately.
This is one of the things that really bugs me about development - and I've been doing it my whole life - the hoops you still have to jump through to properly read an integer. Yes I know, dates and times are even worse. :( just give me my integer, I'm over it. sorry for the rant.
@DanChase see the answer I just added, could use an extension method for that, would be nice if such where available out of the box
27

This should work:

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

Comments

6

Use the GetInt method.

reader.GetInt32(3);

Comments

6

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

Comments

3

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

1 Comment

Do you mean casting to String will not call ToString() already?
1
TxtFarmerSize.Text = (int)reader[3];

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.