P. Pat P. Pat - 2 months ago 16
SQL Question

DateTime format possible to implement on reader.read?

I am very new to c# and visual studios 2015 so any opinions are happily accepted(even bad ones).

Is there a way to directly pull out DateTime to a format of "ddd" using reader.read like for example:

textBox1.Text = Convert.ToDateTime(reader[1].ToString()).ToShortDateString();


I have a very basic grasp of DateTime to string but not sure if the it can be placed in reader.read or not.

My data table contents is this:

Imgur

And my textBox1 shows this:

Imgur

Trying to make that text box show "Thu" instead of the date from my code below:

if (btnSearch.Text == "Search")
{
string sqlStmt = @"SELECT * FROM dbo.tbl_employees WHERE emp_id = @emp_id;";


using (SqlConnection dbCon = new SqlConnection(conStr))
{

SqlCommand dbCmd = new SqlCommand(sqlStmt, dbCon);
dbCmd.Parameters.AddWithValue("@emp_id", txtSearchID.Text);

dbCon.Open();

SqlDataReader reader = dbCmd.ExecuteReader();

while (reader.Read())
{
textBox1.Text = Convert.ToDateTime(reader[1].ToString()).ToShortDateString();
}

reader.Close();
dbCon.Close();
}
}


Sql:

[day_received] Date NOT NULL,


Thanks.

Answer
using(var reader = cmd.ExecuteReader())
{
  if(reader.Read())
  {
    /// Considering GetDateTime returns a DateTime object...
    DateTime dtTemp = reader.GetDateTime(fieldIndex);
    textBox1.Text = dtTemp.toString("dddd");
  }
}

Is this what you are looking for?

Comments