Reputation: 551
I want to find current day of week in c# ASP.Net like:
System.DateTime.Now.DayOfWeek.ToString();
This code works well in a console application, but when I try to store the value of this line in a string in ASP.Net website it returns nothing.
Can anyone help?
StringBuilder message = null;
protected void Page_Load(object sender, EventArgs e)
{
var dayofweek = System.DateTime.Now.DayOfWeek.ToString();
String conn = "Data Source=.;Initial Catalog=OCSI;Integrated Security=True";//conne
SqlConnection sqlconne = new SqlConnection(conn);
string selectSQL = "SELECT lec FROM schedule WHERE [day]='" + dayofweek +"'";
SqlCommand cmd = new SqlCommand(selectSQL, sqlconne);
SqlDataReader reader = null;
try
{
sqlconne.Open();
reader = cmd.ExecuteReader();
message = new StringBuider();
while (reader.Read())
{
message.Append(reader["lec"].ToString());
//question what are you using message for ...?
Label3.Text = dayofweek;
}
reader.Close();
}
catch (Exception ex)
{
Response.Write(ex.Mesage);
}
finally
{
sqlconne.Close();
// you neeed to Dispose of all other objects here too
// StringBuilder Object
// SqlDataReader Object
//SqlCommand Object..
//Look into wrapping your Connection / Command Sql Dataobject around a using() {}
}
I want to use current day in where clause SQL Query to get data relevant to current day from database table.
I used var as
protected void Page_Load(object sender, EventArgs e)
{
String conn = "Data Source=.;Initial Catalog=OCSI;Integrated Security=True";//conne
SqlConnection sqlconne = new SqlConnection(conn);
var testDay = DateTime.Now.DayOfWeek.ToString();
// string selectSQL = "SELECT lec FROM schedule WHERE [day]='" + dayofweek +"'";
string selectSQL = string.Format("SELECT lec FROM schedule WHERE [day]= {0}", testDay);
SqlCommand cmd = new SqlCommand(selectSQL, sqlconne);
SqlDataReader reader;
try
{
sqlconne.Open();
reader = cmd.ExecuteReader();
while (reader.Read())
{
message += reader["lec"].ToString();
Label3.Text = testDay;
}
reader.Close();
}
catch
{
}
finally
{
sqlconne.Close();
}
Upvotes: 3
Views: 19572
Reputation: 4399
As an integer value (system sets sunday's as 0) =
int day = (int)DateTime.Now.DayOfWeek;
Upvotes: 0
Reputation: 18843
if everything is working fine when you remove the where clause then change the Where clause to be something like this
string selectSQL = string.Format("SELECT lec FROM schedule WHERE dbo.schedule.day = {0} ", testDay);
I would also change the name of the field day to something like DayName or something if day is a Reserved word don't use it.. look at this link for Reserved Words in SQL Reserved SQL Words
Upvotes: 0
Reputation: 18843
Also try changing your sql string to this
string selectSQL =
string.Format("SELECT lec FROM schedule WHERE [day]= {0}", dayofweek);
Upvotes: 0
Reputation: 18843
Wep page is the value defined as a public , static, or property..
if you write
var testDay = DateTime.Now.DayOfWeek.ToString();
the results will = "Friday";
Upvotes: 3