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 ou
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.
TxtFarmerSize.Text = (int)reader[3];
Use the GetInt method.
reader.GetInt32(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);
This should work:
txtfarmersize = Convert.ToInt32(reader["farmsize"]);
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