System.Indexoutofrangeexception Sqldatareader

Asked

Viewed 199 times

0

Hello, I am trying to make a code read what is in the SQL Server Database, but I have this error:

System.IndexOutOfRangeException: Pontos
   em  System.Data.ProviderBase.FieldNameLookup.GetOrdinal(String fieldName)
   em  System.Data.SqlClient.SqlDataReader.GetOrdinal(String name)
   em  System.Data.SqlClient.SqlDataReader.get_Item(String name)

Code:

public Usuario InitUsuario(SqlDataReader reader)
{
    Usuario usuario = new Usuario();
    usuario.pontos = (int)reader["Pontos"];
    return usuario;
}
  • 1

    There is no column called Pontos what was returned by the query.

  • But I created the Stitches column.

  • @Leonardo Araujo, could post the columns of the database ?

  • Maybe the column is "stitches"

  • http://prntscr.com/gmmfha

  • Have debug and see if you really have it, this screen doesn’t mean anything.

  • and select the query ?

  • Like, I just created the table and placed the column, not by query.

  • and where that came from SqlDataReader ?

  • I don’t understand, Sqldatreader is by query?

  • If I query the table, in the query it says that it exists

  • Please send the complete code for the data reading.

Show 7 more comments

1 answer

3


First point, as it is a Datareader, you have to iterate on it to be able to read some value, even if the query returns only one line. Change your code to the following:

public Usuario InitUsuario(SqlDataReader reader)
{
    if(reader.HasRows)
    {
        while(reader.Read())
        {
            Usuario usuario = new Usuario();
            usuario.pontos = (int)reader["Pontos"];
            return usuario;
        }
    }

    reader.Close();
}

I don’t know in which situation you will use Reader, but if it is the case, as it is only a user you are probably reading, it is better to use a Dataadapter, or get used to Microorm’s, like Dapper.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.