简体   繁体   中英

How to take only time part of TIMESTAMP without time zone and put it inside datagridview using C#?

I have a problem with converting DateTime format into datagridview. Basically the case is this: in database I have 4 columns with type: TIMESTAMP without time zone. I reach for that data from database using SQL query and what I want is to write TIMESTAMP without time zone type without date, only time.

Ex. first row column "Arrival" has value: "2017-03-08 14:44:32", I want to take "14:44:32" from that cell and place it into datagridview, column "Arrival". When I make a command like:

 foreach (DataRow row in dt.Rows)
 {
     string spremanje_string = row["Arrival"].ToString();
     string pretvorba = spremanje_string.Substring(spremanje_string.IndexOf(' ') + 1);
     row["Arrival"] = DateTime.ParseExact(pretvorba, "HH:mm:ss", CultureInfo.InvariantCulture);
 }

(Dont mind foreach, its just part of code from that loop).

C# gives me a error saying:

An unhandled exception of type 'System.FormatException' occurred in mscorlib.dll

Additional information: String was not recognized as a valid DateTime.

I can think of 3 solutions,

  1. Set DefaultCellStyle easiest method
  2. Set the format after you filled your dataGridView (what you tried in your ForEach).
  3. Set the format before the data goes in.

Example nr 1:

dataGridViewName.Columns["columnName"].DefaultCellStyle.Form‌​‌​at = "HH:mm:ss";

Example nr 2:

foreach (DataRow row in dt.Rows)
{
    string dateTime = row["Arrival"].ToString();
    string time = dateTime.Split(' ')[1];
    //Do not convert to DateTime, no use if you will only use it to display (string)
    row.Cells["Arrival"].Value = time;
}

Example nr 3:

When adding the date value to the DataGridView (this won't work with a DataSource as far as I know):

dateTimeValue.TimeOfDay.ToString()  

If your row["Arrival"] is DateTime you can use .TimeOfDay.

This gives you a TimeSpan.

So you have several possible solutions here:

  • You can change the type of row["Arrival"] to be TimeSpan and get TimeOfDay when your read from Database.

  • If you just need to display the time (no sorting, editing) use .ToString("HH:mm:ss") on the DateTime to get a string.

  • If you are using WPF you can use a DataGridTextColumn and StringFormat={HH:mm:ss} in your binding

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM