Split Date and Time in DataGridView - c#

I have a DATETIME column in DataGridView, which contains both the date and the time. I need to separate the date from the time. The date should be displayed in one column and the time in another column.
I've tried something but it just gives either the date only or the time only; however, I needed them both separately.

You may format the cells of a column:
dataGridView.Columns[#].DefaultCellStyle.Format = "MM/dd/yyyy";
dataGridView.Columns[#].DefaultCellStyle.Format = "HH:mm";
Replace # with target columns.
All of the regular DateTime formatting options are available for the above example. You may tailor it to your needs. To review the available options, refer to MSDN's Custom Date and Time Formatting Strings documentation page.

You can simply do (example):
DateTime dt = DateTime.Now;
string date = dt.ToShortDateString();
string time = dt.ToShortTimeString();
Then, insert into corresponding DataGridView's cell:
dataGridView1[0, 1].Value = date;
dataGridView1[0, 2].Value = time;

Related

How to make format mask in DataGridView cell?

I need to make a format/mask in a cell that prevents the user from entering data that isn't relevant.
The column cell contains date values like "MM/YYYY" without a day value.
I tried the following to make this definition but without success:
dataGridView1.Columns[0].DefaultCellStyle.Format = "##/####" // || dd/yyyy
Also, I tried to go to the properties of DataGridView and define Format from there.
The method you're using for formatting is a valid approach. There are a few issues that may be happening here. Please ensure:
The underlying data is of type DateTime and not type string. Type string will not apply the format as expected. (See columns 1 and 2 in example below.)
The individual DataGridViewTextBoxCell.Style.Format isn't being set to something different than your desired format. This would override the column formatting. (See column 3 in example below.)
EXAMPLE
this.dataGridView1.ColumnCount = 4;
this.dataGridView1.RowCount = 1;
this.dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;
DateTime date = DateTime.Now;
this.dataGridView1[0, 0].Value = date;
this.dataGridView1[1, 0].Value = date.ToString();
this.dataGridView1[2, 0].Value = date.ToString("MM/yyyy");
this.dataGridView1[3, 0].Value = date;
this.dataGridView1[3, 0].Style.Format = "MM/yyyy";
this.dataGridView1.Columns[0].DefaultCellStyle.Format = "dd/yyyy";
this.dataGridView1.Columns[1].DefaultCellStyle.Format = "dd/yyyy";
this.dataGridView1.Columns[2].DefaultCellStyle.Format = "dd/yyyy";
this.dataGridView1.Columns[3].DefaultCellStyle.Format = "dd/yyyy";
As you can see from the output:
Columns[0] contains a DateTime and correctly formats as "dd/yyyy".
Columns[1] contains a string and cannot be reformatted to "dd/yyyy".
Columns[2] contains a formatted string and cannot be reformatted to "dd/yyyy".
Columns[3] contains a DateTime and formatting is overridden by the cell format "MM/yyyy".
To correct these issues, just set your cell value using the DateTime object and not any string representation.
In the case where you are getting this data from some outside source and it's already of type string, you can Parse it, but note that the missing portions of the DateTime object will be defaulted and there's really nothing you can do about that without having the original full data:
DateTime date = DateTime.Parse("10/2016");
Console.WriteLine("Output: {0}", date.ToString());
// Output: 10/1/2016 12:00:00 AM
Validation
If validating user input (and losing formatting on edits) is your main concern, consider the following method for validation to cancel an invalid edit:
private void DataGridView1_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
{
DateTime parsed;
if (!DateTime.TryParse(e.FormattedValue.ToString(), out parsed))
{
this.dataGridView1.CancelEdit();
}
}
Coupled with this answer for reapplying your format using the DataGridView.CellFormatting event handler. (Note that this also negates the need to ensure your data types are not string, but is more costly due to the event being triggered often.)

Minimum and maximum data form Data Table

I have data Table with four columns: Date, isin, Price and State.
I need to get minimum and maximum date from the Date column.
I'm using this code and it works fine with one file however with other file it shows me wrong maximum date.
DateTime stDate = Convert.ToDateTime((excleTable.Compute("min(date)", string.Empty)));
DateTime eDate = Convert.ToDateTime((excleTable.Compute("max(date)", string.Empty)));
For example on first row i have 02/27/2015 and on last row i have 03/31/2015 but it reads only till 03/09/2015 which is incorrect.
Any ideas what should i do ?
Looks like your column type isn't DateTime. If you can fix that than make sure that your DataTable has DateTime type for column date, otherwise you can use LINQ's Max and Min and convert your column to DateTime like:
DateTime stDate = dt.AsEnumerable()
.Max(r => Convert.ToDateTime(r.Field<string>("date")));
DateTime eDate = dt.AsEnumerable()
.Min(r => Convert.ToDateTime(r.Field<string>("date")));
You may have to use DateTime.ParseExact for converting to DateTime, if your string values doesn't correspond to default/available DateTime formats, like:
DateTime stDate = dt.AsEnumerable()
.Max(r => DateTime.ParseExact(r.Field<string>("date"),
"MM/dd/yyyy",
CultureInfo.InvariantCulture));

How to remove year from datetime object?

I have a gridview that is bound to a datatable from a db. One of the columns is a datetime field which I got to read in shortdate mode (mm/dd/yyyy). However, I was wondering if there was any easy to remove the year from the date time either in the cell or at the time of display.
//Convert the "date" column to only appear in mm/dd format
foreach (GridViewRow row in GridView1.Rows)
{
String myS = row.Cells[2].Text;
DateTime dt = DateTime.Parse(row.Cells[2].Text);
row.Cells[2].Text = dt.ToShortDateString();
}
Use the standard ToString date formatter, with capital MM meaning "month month" and lower-case dd "day day"
row.Cells[2].Text = dt.ToString("MM/dd");
The answer really depends on if you want to support I18N/L10N. If you're interested in your date coming out something like "June 15" in en-US or "15. juni" in da-DK, you could use:
row.Cells[2].Text = dt.ToString("M");
If, on the other hand, you're interested in your date always coming out "06/15", regardless of culture, you can use:
row.Cells[2].Text = dt.ToString("MM/dd");
As far as I can tell, there's no internationalized standard date/time format for Month/Day, but you can check out the full list of standard formats for yourself at MSDN - Standard Date and Time Format Strings.

Filter a DataTable using DateTime value

Updated:
I am trying to filter a DataTable based on a particular date.
My datatable has a column "whn" which contains dates. A Sample date from the DataTable:
{21/02/2012 10:03:53} object {System.DateTime}
Here is the code I am using to try and filter the DataTable:
String datevalue= "21/02/2012 10:03:53";
DataRow[] foundRows;
foundRows = dttemp.Select(String.Format("whn = '{0}'", datevalue));
However this does not work and returns 0 rows. Even though I know that a row containing the date in "datevalue" exists.
Unsure why this is not working, any help is appreciated.
Thanks.
If you want to exactly match the supplied DateTime, including fractions of a second, you should use a DateTime format that has enough precision. Probably the round-trip format ("o") is a good bet:
foundRows = dttemp.Select(String.Format(dttemp.Locale, "whn = '{0:o}'", datevalue));
However, it's more likely you want to match values that fall into a range. For example, if you want all values that have the same date, but any time of day, you could use:
foundRows = dttemp.Select(String.Format(dttemp.Locale, "whn >='{0:o}' AND whn < '{1:o}'",
datevalue.Date, datevalue.AddDays(1).Date));
Similarly if you want all values that are in the same second (but may have fractions of a second), you can use:
DateTime from = dttemp.AddTicks( - (dttemp.Ticks % TimeSpan.TicksPerSecond));
foundRows = dttemp.Select(String.Format(dttemp.Locale, "whn >='{0:o}' AND whn < '{1:o}'",
from, from.AddSeconds(1)));
The call to AddTicks truncates the supplied DateTime to a whole number of seconds, as described in the accepted answer to this StackOverflow question.
Note I used dttemp.Locale to use the correct locale (CultureInfo) in case your DataTable has a locale other than your current culture.
foundRows = dttemp.Select("whn LIKE '{0}'",datevalue);
should probably be
foundRows = dttemp.Select(String.Format("whn LIKE '{0}'",datevalue));
more info here http://www.csharp-examples.net/dataview-rowfilter/
Use = instead of LIKE
foundRows = dttemp.Select(String.Format("whn = '{0}'", datevalue));

How to format DateTime columns in DataGridView?

I'm using a DataGridView with object data binding to display information about logging entities in a system, retrieved via SOAP from a remote service.
One of the columns is called "Last action" and means the last time the entity logged a message. It is a System.DateTime value. When I read the SOAP response (example below), he timestamp obviously contains all the information, up to second fractions.
<LoggingEntity>
<host>marty86ce</host>
<process>10148</process>
<logger>http_core</logger>
<appName>httpd</appName>
<ffda>true</ffda>
<lastAction>2010-10-27T12:00:19.5117509Z</lastAction>
<lastHeartbeat>0001-01-01T00:00:00</lastHeartbeat>
<channelId>em_9BA2A2B4D0B6E66</channelId>
<ffdaChannelId>em_E7C8D1D4DE8EEB9</ffdaChannelId>
</LoggingEntity>
When I display it on the table, I instead can read up to the minutes
I use the following code to do the data binding when I press the refresh button
public void RefreshEntities()
{
IEntityManagement management = EntityPlugin.GetProxy();
LoggingEntity[] result = management.FindLoggingEntities(new TemplateQuery { ffdaSpecified = true, ffda = true }); //Remote invocation
Invoke(new MethodInvoker(delegate { gridEntities.DataSource = result; })); //THIS does the data binding from the array
Invoke(new MethodInvoker(delegate { btnRefresh.Enabled = true; }));
}
I would like to know how to control column formatting of data bound values. I think that the format dd/MM/yyyy hh:mm comes from my system's settings. How to override formatting settings programmatically?
Thank you in advance
Full solution code on Subversion (FFDAGui program) for the Logbus-ng open source project.
If it is a windows form Datagrid, you could use the below code to format the datetime for a column
dataGrid.Columns[2].DefaultCellStyle.Format = "MM/dd/yyyy HH:mm:ss";
EDIT :
Apart from this, if you need the datetime in AM/PM format, you could use the below code
dataGrid.Columns[2].DefaultCellStyle.Format = "MM/dd/yyyy hh:mm:ss tt";
Use Column.DefaultCellStyle.Format property or set it in designer
You can set the format you want:
dataGridViewCellStyle.Format = "dd/MM/yyyy";
this.date.DefaultCellStyle = dataGridViewCellStyle;
// date being a System.Windows.Forms.DataGridViewTextBoxColumn
I used these code Hope it could help
dataGridView2.Rows[n].Cells[3].Value = item[2].ToString();
dataGridView2.Rows[n].Cells[3].Value = Convert.ToDateTime(item[2].ToString()).ToString("d");
You can set the format in aspx, just add the property "DateFormatString" in your BoundField.
DataFormatString="{0:dd/MM/yyyy hh:mm:ss}"
Published by Microsoft in Standard Date and Time Format Strings:
dataGrid.Columns[2].DefaultCellStyle.Format = "d"; // Short date
That should format the date according to the person's location settings.
This is part of Microsoft's larger collection of Formatting Types in .NET.
string stringtodate = ((DateTime)row.Cells[4].Value).ToString("MM-dd-yyyy");
textBox9.Text = stringtodate;

Categories

Resources