Issue - FieldNameLookup.GetOrdinal

Peter_1985 2,686 Reputation points
2024-08-31T23:35:37.13+00:00

Hi,

To error

at System.Data.ProviderBase.FieldNameLookup.GetOrdinal(String fieldName)

at System.Data.SqlClient.SqlDataReader.GetOrdinal(String name)

at System.Data.SqlClient.SqlDataReader.get_Item(String name)

at Own_rec._Default.Page_Load(Object sender, EventArgs e)

on this line

tb_date_from.Text = reader["date_from"].ToString().Trim();

How to resolve it?

C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
11,010 questions
{count} votes

Accepted answer
  1. Viorel 118K Reputation points
    2024-09-01T06:27:54.0366667+00:00

    Make sure that the query includes the column called “date_from”.

    Show details about your code from Page_Load.

    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. Karen Payne MVP 35,436 Reputation points
    2024-09-02T10:42:10.81+00:00

    Look at your SQL statement, get the ordinal position and match it using the proper type via the SqlDataReader via one of the methods using Get....

    Here date_from is a DateTime, second column which means ordinal position 1.

    var statement = "SELECT Id, date_from FROM SomeTable;";
    
    using var cn = new SqlConnection("TODO");
    using var cmd = new SqlCommand(statement, cn);
    
    cn.Open();
    SqlDataReader? reader = cmd.ExecuteReader();
    reader.Read();
    
    tb_date_from.Text = reader.GetDateTime(1).ToString(CultureInfo.InvariantCulture);
    

    Or

    var statement = "SELECT Id, date_from FROM SomeTable;";
    
    using var cn = new SqlConnection("TODO");
    using var cmd = new SqlCommand(statement, cn);
    
    cn.Open();
    SqlDataReader? reader = cmd.ExecuteReader();
    reader.Read();
    
    tb_date_from.Text = reader.GetFieldValue<DateTime>(reader.GetOrdinal("date_from")).ToString(CultureInfo.InvariantCulture);
    
    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.