1

help! i get an error when i run the program on reader

i want to select the last column of DateToday but i get an error on reader

connection.Open();

OleDbCommand efgh = new OleDbCommand();
efgh.Connection = connection;
efgh.CommandText = "SELECT LAST(DateToday) FROM SalesPerDay";
OleDbDataReader reader = efgh.ExecuteReader();
if (reader.Read())
{
    //this part gives me IndexOutOfRangeException:  
    label2.Text = reader["DateToday"].ToString();
}

connection.Close();
2
  • 1
    Change CommandText to "SELECT LAST(DateToday) as DateToday FROM SalesPerDay" Commented Mar 14, 2016 at 11:42
  • or label2.Text = reader[0].ToString(); Commented Mar 14, 2016 at 11:43

3 Answers 3

2

Your problem is that when you perform a Last function you lose the column name in the SQL. so when you reference the column by name, in the code, the name doesn't exist hence the IndexOutOfRangeException

either name the column i.e.

SELECT LAST(DateToday) as DateToday

or switch to index referencing i.e.

reader[0]

also as you are only returning single value you could switch to a scalar get rather than a row get

label2.Text = efgh.ExecuteScalar().ToString();
Sign up to request clarification or add additional context in comments.

Comments

0

Try to change your query by providing the alias name to your column as

SELECT LAST(DateToday) as DateToday FROM SalesPerDay

or else you can try to use

label2.Text = reader[0].ToString();

Comments

0

Expanding on the correct answers given by others, you could also try checking if your column exists in your query and has a value using syntax like this:

var colIndex = reader.GetOrdinal("DateToday");
if (colIndex >= 0 && !reader.IsDBNull(colIndex))
{
    var date = reader.GetDateTime(colIndex).ToShortDateString();
    label2.Text = date;
}

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.