简体   繁体   中英

DataGrid copy to clipboard DateTime format issue

I have a data grid in WPF that I am filling with an SQL query result through a data table. However, when I copy the grid to clipboard, it is always copied with the full date/time format. Here is what I am doing:

I have an SQL statement to read some data including date field from the DB as:

searchProDateSQLCMD.CommandText = "select pName, convert(date, pDate), FROM [Professionals] WHERE pName = @parName"

I fill a data table with the result as:

dTableAdpater = new SqlDataAdapter(searchProDateSQLCMD);
dTable = new DataTable("Professionals");
dTableAdpater.Fill(dTable);

I then set the column for the grid to display the info:

DataGridTextColumn jDateCl = new DataGridTextColumn();
pDateCl.Binding = new Binding("pDate");

pDateCl.Binding.StringFormat = "{0:d}";

I then bind the grid with the column I created

SearchResultGrid.Columns.Add(pDateCl);

When I try to copy that column:

SearchResultGrid.SelectAllCells();
SearchResultGrid.ClipboardCopyMode = DataGridClipboardCopyMode.IncludeHeader;

I get the time copied; but with the time format is (dd/MM/yyyy 12:00:00 AM) , even though I use convert() in SQL, and {0:d} in the column.

What am I doing wrong? What am I missing to just get the date on copy without the time?

Unfortunately, this is a current DataGrid 's implementation limitation.

As you can see in the reference sources , the DataGrid renders the cell's contents into the clipboard using a simple ToString() call, without providing any format. This call will use the CultureInfo.CurrentCulture and the default format for the DateTime , hence the result you get.

So you have at least two options:

  • Set the main thread's CultureInfo to the the desired date/time format. Note that this will affect all the ToString() calls on any DateTime objects, so maybe this is not suitable for you.

  • Instead of using a DateTime column, use a string column and do the conversion on the server side. Not a good approach however, because you loose all the benefits of the DateTime type.

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