DateTime Oveload - c#

I am trying to have this output in my label
example:April 20,2016
but I get 4/20/2016:1200:00:AM instead
I tried to modified it but can't figure this error out
no overload for method takes 1 arguments
cause by this code
lblDate.Text = rdr.GetValue(4).ToString("MMMM d,yyyy");
This is the entire code.
private void GetData()
{
SqlConnection con = new SqlConnection("Data Source = localhost\\SQLEXPRESS;Initial Catalog = MejOnlineManagementDB00;Integrated Security=True;");
con.Open();
SqlCommand cmd = new SqlCommand(#"SELECT orderProdName,orderProdType,orderQuantity,orderStatus,orderDateOrdered
FROM orders2
WHERE orderCustomer='"+DropDownList1.SelectedItem.Value.ToString()+"'",con);
SqlDataReader rdr = cmd.ExecuteReader();
if (rdr.HasRows)
{
while (rdr.Read())
{
lblProdName.Text = rdr.GetValue(0).ToString();
lblProdType.Text = rdr.GetValue(1).ToString();
lblQuantity.Text = rdr.GetValue(2).ToString();
lblStatus.Text = rdr.GetValue(3).ToString();
lblDate.Text = rdr.GetValue(4).ToString("MMMM d,yyyy");
}
}
con.Close();
}

The problem is that you are using the Object.ToString() method. This method, does not have arguments. If you want to convert it into a date, you might try this:
DateTime dt = DateTime.Parse(rdr.GetValue(4).ToString())
lblDate.Text = dt.ToString("MMMM d,yyyy");
Edit:
Please note, that if the date column in your database contains null-values, the parse methode will throw an exception. So testing for null is mandatory.
String s = Convert.ToString(rdr.GetValue(4));
if(!String.IsNullOrEmpty(s))
{
DateTime dt = DateTime.Parse(s);
lblDate.Text = dt.ToString("MMMM d,yyyy");
}

The rdr.GetValue(int32) method returns an object and not DateTime.
https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldatareader.getvalue(v=vs.110).aspx
Parse your the returned value into a DateTime object and then use the ToString method.

That will work only for DateTime value, you can convert the value in DateTime first:
lblDate.Text = Convert.ToDateTime(rdr.GetValue(4)).ToString("MMMM d,yyyy");

Related

Format Datagridview column to time just shows hh:mm:ss

I'm populating a datagridview with data and one of the columns should be shown as time i.e. hh:mm:ss.
The data is extracted from the Access database and successfully populates in the datagridview. The column I want to show as time is populated in the access database as "Number". As you will see I covert it down to seconds using /86400 within the select query.
When I try to convert the column using DefaultCellStyle.Format = "hh:mm:ss tt", the entire column of data is replaced with just "hh:mm:ss tt" in each cell i.e. there are no longer numbers, its just hh:mm:ss tt in every cell.
Below is my code - can anyone advise what I am doing wrong?
string strProvider =
"Provider = Microsoft.ACE.OLEDB.12.0; Data Source = P:\\JC_StockFile\\Mitel\\Mitel.accdb";
string strSql =
"SELECT [MidnightStartDate], [Agent Name], [LoginTime], [LogoutTime], [ShiftDuration]/86400 as ShiftDuration " +
"FROM login_data " +
"WHERE [MidnightStartDate] > #LeDate";
OleDbConnection con = new OleDbConnection(strProvider);
OleDbCommand cmd = new OleDbCommand(strSql, con);
con.Open();
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#LeDate", DateTime.Today.AddDays(-3) );
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
DataTable scores = new DataTable();
da.Fill(scores);
dataGridView1.DataSource = scores;
dataGridView1.Columns["ShiftDuration"].DefaultCellStyle.Format = "hh:mm:ss tt";
I believe this property works like other String Formats. Edit: I think actually you just have an upper case issue:
Try this:
dataGridView1.Columns["ShiftDuration"].DefaultCellStyle.Format = "HH:mm:ss";
Reference:
https://msdn.microsoft.com/en-us/library/zdtaw1bw(v=vs.110).aspx
Microsoft suggest to use CellFormatting event
private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
// If the column is the ShiftDuration column, check the
// value.
if (this.dataGridView1.Columns[e.ColumnIndex].Name == "ShiftDuration")
{
ShortFormDateFormat(e);
}
}
private static void ShortFormDateFormat(DataGridViewCellFormattingEventArgs formatting)
{
if (formatting.Value != null)
{
try
{
DateTime theDate = DateTime.Parse(formatting.Value.ToString());
String dateString = theDate.toString("hh:mm:ss tt");
formatting.Value = dateString;
formatting.FormattingApplied = true;
}
catch (FormatException)
{
// Set to false in case there are other handlers interested trying to
// format this DataGridViewCellFormattingEventArgs instance.
formatting.FormattingApplied = false;
}
}
}

Getting data from database by getting date from DateTimePicker

I am trying to get data in gridview on the basis of the date that is entered in dateTimePicker. But, I am getting null reference runtime error on if condition where I have used equals function to compare two strings.
ReportFrom.cs
private void button1_Click(object sender, EventArgs e)
{
string date = dateTimePicker.Value.ToShortDateString();
reportLayer.MakeDailyReport(date, dataGridViewReport);
}
ReportLayer.cs
private SqlConnection con = new SqlConnection("Data Source=CHAMP-PC;Initial Catalog=ProcessSale;Integrated Security=True");
private SqlCommand cmd;
private SqlDataAdapter adapt;
public void MakeDailyReport(string givenDate, DataGridView view)
{
try
{
con.Open();
DataTable dt = new DataTable();
cmd = new SqlCommand("SELECT Date FROM FinalSales where Date = #datePicker", con);
cmd.Parameters.AddWithValue("#datePicker", givenDate);
cmd.ExecuteNonQuery();
object dateObject = cmd.ExecuteScalar();
string dateObjectstring = Convert.ToString(dateObject);
string givenDateString = Convert.ToString(givenDate);
// string DBdate = dateObject.ToString();
if (dateObject.Equals(givenDate))
{
adapt = new SqlDataAdapter("SELECT Date FROM FinalSales where Date = " + givenDate + "", con);
if (adapt != null)
{
adapt.Fill(dt);
view.DataSource = dt;
}
else
{
MessageBox.Show("No Record found againts that date");
con.Close();
}
}
else
{
con.Close();
}
}
catch (Exception a)
{
MessageBox.Show(a.Message);
con.Close();
}
}
Have a look here:
Handling ExecuteScalar() when no results are returned
Additionally: Be careful with the call to Equals(). Currently you are comparing
two strings. One with a ShortDate value One with the default ToString().
Event if the dates are equal, this might return false.
A better solution would be handling both values as DateTime and use the == operator.
Thomas

Allow to pass null values with DateTime.Parse(date.text) method in C#

I have the following form:
once I click button Its working like this , all above parameters pass to GetData method
protected void btnShow_Click(object Sender, EventArgs e)
{
ShowReport();
}
private void ShowReport()
{
//Reset
ReportViewer1.Reset();
//DataSource
DataTable dt = GetData(type.Text, category.Text,subsidary.Text,country.Text, DateTime.Parse(date.Text));
............................
}
this is GetData method
private DataTable GetData(string type, string category, string country, string subsidary, string dateHERE)
{
// date = date.Value.ToOADate();
DateTime? mydate = null;
DateTime date2;
bool check = DateTime.TryParse(dateHERE, out date2);
if (check)
{
mydate = date2;
}
DataTable dt = new DataTable();
string connStr = System.Configuration.ConfigurationManager.ConnectionStrings["AB_ReportEntities"].ConnectionString;
using (SqlConnection cn = new SqlConnection(connStr))
{
SqlCommand cmd = new SqlCommand("FindIncomplete_Products", cn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#type", SqlDbType.NVarChar).Value = type;
cmd.Parameters.Add("#category", SqlDbType.NVarChar).Value = category;
cmd.Parameters.Add("#country", SqlDbType.NVarChar).Value = country;
cmd.Parameters.Add("#subsidary", SqlDbType.NVarChar).Value = subsidary;
cmd.Parameters.Add("#date", SqlDbType.Date).Value = mydate;
SqlDataAdapter adp = new SqlDataAdapter(cmd);
adp.Fill(dt);
}
return dt;
}
I cannot get result when Date field has null values in above form , I'm getting the following error:
System.FormatException: String was not recognized as a valid DateTime.
Change your method like this:
private DataTable GetData(string type, string category, string country, string subsidary,string date)
{
DateTime? mydate = null;
DateTime date2;
bool check = DateTime.TryParse(date, out date2);
if (check)
{
mydate = date2;
}
}
And then call it like this:
DataTable dt = GetData(type.Text, category.Text,subsidary.Text,country.Text, date.Text);
Obviously passing a value that cannot be parsed to a DateTime will throw an exception using DateTime.Parse so use DateTime.TryParse instead:
The DateTime.TryParse(String, DateTime) method is similar to the DateTime.Parse(String) method, except that the TryParse(String, DateTime) method does not throw an exception if the conversion fails.
Source: DateTime.TryParse
example usage:
DateTime d2;
bool success = DateTime.TryParse(date.Text, out d2);
//if successful, d2 will be set to the value of the string.
You can use this extension:
public static DateTime? TryGetDateTime(this string item, IFormatProvider provider = null)
{
if (provider == null) provider = CultureInfo.CurrentCulture;
DateTime dt;
bool success = DateTime.TryParse(item, provider, DateTimeStyles.None, out dt);
if (success) return dt;
return null;
}
Then change your method call in this way:
DataTable dt = GetData(type.Text,
category.Text,
subsidary.Text,
country.Text,
date.Text.TryGetDateTime());

How can I pass DateTime format to MS sql server in a stored procedure?

I hope you could help me in my project.
I have been trying to solve this issue long time ago and it doesn't work.
I'm trying to pass a Date time from c# to MS sql server, note that the server
stored datetime with format '1900-01-01 00:00:00.000'
it's work perfectly when I use it locally, but when I upload page into a server I get error.
string connectionString;
SqlConnection mySqlConnection;
connectionString = ConfigurationManager.ConnectionStrings[("connectionNamr")].ConnectionString;
mySqlConnection = new SqlConnection(connectionString);
SqlCommand mySqlComd = new SqlCommand();
SqlDataReader reader;
mySqlComd.CommandText = "ProcedureName";
mySqlComd.CommandType = CommandType.StoredProcedure;
mySqlComd.Connection = mySqlConnection;
SqlParameter depParam = new SqlParameter("#colName1", SqlDbType.NVarChar, 255);
SqlParameter empParam = new SqlParameter("#colName2", SqlDbType.NVarChar, 20);
SqlParameter startDateParam = new SqlParameter("#EVcolName3", SqlDbType.DateTime);
SqlParameter endDateParam = new SqlParameter("#colName4", SqlDbType.DateTime);
SqlParameter filterParam = new SqlParameter("#colName5", SqlDbType.NVarChar, 20);
depParam.Value = string.Empty;
empParam.Value = employeeID;
DateTime datet = new DateTime(year,month,day);
string datet1 = datet.ToString();
//string datet1 = datet.ToUniversalTime().ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fff'Z'");
// datet1 = datet1.Substring(0, 19);
startDateParam.Value = Convert.ToDateTime(datet1.Trim()); ;
endDateParam.Value = Convert.ToDateTime(datet1.Trim()); ;
filterParam.Value = string.Empty;
mySqlComd.Parameters.Add(depParam);
mySqlComd.Parameters.Add(empParam);
mySqlComd.Parameters.Add(startDateParam);
mySqlComd.Parameters.Add(endDateParam);
mySqlComd.Parameters.Add(filterParam);
mySqlConnection.Open();
mySqlComd.ExecuteNonQuery();
reader = mySqlComd.ExecuteReader(CommandBehavior.CloseConnection);
while (reader.Read())
{
attendance_date = reader["SITE_IN_TIME"].ToString();
}
mySqlConnection.Close();
return attendance_date;
}
catch (Exception exp)
{
return "Error, Exception: " + exp;
}
The problem with the date format is because you are converting it to a string and then back to a DateTime value. Depending on the culture settings on the specific server this may or may not work. It may also misinterpret the data, e.g. transforming a date from 2013-10-12 to 2013-12-10.
Just use the DateTime value that you already have:
DateTime datet = new DateTime(year,month,day);
startDateParam.Value = datet;
endDateParam.Value = datet;
Side note:
"note that the server stored datetime with format '1900-01-01
00:00:00.000'"
No, it doesn't. A datetime value is a numeric value representing a point in time, it's not stored as text.
You can just directly pass DateTime to your parameter, there is no need to convert it to string and back to date again:
DateTime datet = new DateTime(year,month,day);
startDateParam.Value = datet;
endDateParam.Value = datet;

Convert SQL Date time format to String

when reading SQl Date time field , only i can take the date with time ..how to get only date in to text box from Ajax or some method.
this is what i need to do
http://i.stack.imgur.com/n0fgG.jpg
that's how I'm taking the date to text box.
protected void ddlBatch_SelectedIndexChanged(object sender, EventArgs e)
{
String strConnString = ConfigurationManager.ConnectionStrings["CBConnectionString"].ConnectionString;
const String strQuery = "select ItemIdentityCode, Qty, PurchasingPrice, ExpireDate, DiscountRate, IssueMode, Principle, Force from DEL_PurchasesLines where BatchNumber = #BatchNumber";
SqlConnection conPR = new SqlConnection(strConnString);
SqlCommand cmdPR = new SqlCommand();
cmdPR.Parameters.AddWithValue("#BatchNumber", ddlBatch.SelectedItem.Value);
cmdPR.CommandType = CommandType.Text;
cmdPR.CommandText = strQuery;
cmdPR.Connection = conPR;
try
{
conPR.Open();
SqlDataReader sdr = cmdPR.ExecuteReader();
while (sdr.Read())
{
tHFExpiaryDate.Text = sdr["ExpireDate"].ToString();
}
}
catch (Exception ex)
{
//throw ex;
}
finally
{
conPR.Close();
conPR.Dispose();
}
}
Don't convert the raw value to a string in the first place - it should already be a DateTime:
DateTime date = (DateTime) dsr["ExpireDate"];
Then you can convert it into whatever format you're interested in:
// TODO: Consider specifying the culture too, or specify a standard pattern.
tHFExpiaryDate.Text = date.ToString("MM/d/yyyy");
It's important to separate the question of "How can I get the data from the database in an appropriate type?" from "How should I present the data to the user?"
Try something like:
DateTime.ParseExact(sdr["ExpireDate"].ToString(), "MM/d/yyyy", CultureInfo.InvariantCulture)
In your sample:
tHFExpiaryDate.Text = DateTime.ParseExact( ((DateTime)dt.Rows[0][0]).ToString("MM/d/yyyy"), "MM/d/yyyy", System.Globalization.CultureInfo.CurrentCulture).ToString("MM/d/yyyy"));
This always works for me
protected String getDate(string date)
{
DateTime dDate;
string sdate = null;
if (!string.IsNullOrEmpty(date.ToString()))
{
dDate = DateTime.Parse(date.ToString());
sdate = dDate.ToString("dd/MM/yyyy");
sdate = dDate.ToLongDateString();
}
return sdate;
}
Other date format example http://www.dotnetperls.com/datetime-format

Categories