0

I want to fetch the maximum value of date from the table. But I always get an 'OutofRangeException' error. I changed my query several times.

  • Due_Date column has date data type
  • Due_Date_Sample is a string var
  • Due_Date_var is a DateTime var

My code:

using (SqlConnection sqlCon = new SqlConnection(Main.connectionString))
{
    string commandString = "SELECT TOP 1 FORMAT(Due_Date,'dd-MM-yyyy') FROM Transactions WHERE Plot_Code='" + Plot_Code_var + "' ORDER BY Due_Date DESC;";

    SqlCommand sqlCmd = new SqlCommand(commandString, sqlCon);

    sqlCon.Open();

    SqlDataReader dr = sqlCmd.ExecuteReader();

    while (dr.Read())
    {
        date_control_var = 2;
        Due_Date_Sample = (dr["Due_Date"].ToString());
        Due_Date_var = DateTime.Parse(Due_Date_Sample.ToString());
    }

    dr.Close();
}
5
  • What 's line of code it throw the exception? Commented Jan 30, 2019 at 4:08
  • Check to see if it is null. The database excepts a null for DateTime but c# doesn't. Commented Jan 30, 2019 at 4:09
  • Due_Date_Sample = dr["Due_Date"].ToString(); Commented Jan 30, 2019 at 4:10
  • I am checking for null in another try catch.... This piece of code runs when the value is not null Commented Jan 30, 2019 at 4:10
  • 1
    Please, also consider using parameters instead of string concatenation in your SQL. Commented Jan 30, 2019 at 4:19

2 Answers 2

7

You need to give an alias to the selected value, e.g.: FORMAT(Due_Date,'dd-MM-yyyy') as Due_Date

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

Comments

1

You can do this:

using (SqlConnection sqlCon = new SqlConnection(Main.connectionString))
                    {
                        string commandString = "SELECT TOP 1 FORMAT(Due_Date,'dd-MM-yyyy') as Due_Date FROM Transactions where Plot_Code='" + Plot_Code_var + "' ORDER BY Due_Date DESC;";

                        SqlCommand sqlCmd = new SqlCommand(commandString, sqlCon);
                        sqlCon.Open();
                        SqlDataReader dr = sqlCmd.ExecuteReader();
                        while (dr.Read())
                        {
                            date_control_var = 2;
                            Due_Date_Sample = (dr["Due_Date"].ToString());
                            Due_Date_var = DateTime.Parse(Due_Date_Sample.ToString());

                        }
                        dr.Close();
                    }

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.