Format date from SQLCE to display in DataGridView
Posted
by Ruben Trancoso
on Stack Overflow
See other posts from Stack Overflow
or by Ruben Trancoso
Published on 2009-11-02T18:31:46Z
Indexed on
2010/05/23
2:00 UTC
Read the original article
Hit count: 500
hi folks, I have a DataGridView bound to a table from a .sdf database through a BindSource. The date column display dates like "d/M/yyyy HH:mm:ss". e.: "27/2/1971 00:00:00".
I want to make it display just "27/02/1971" in its place. I tried to apply DataGridViewCellStyle {format=dd/MM/yyyy} but nothing happens, event with other pre-built formats.
On the the other side, there's a Form with a MasketTextBox with a "dd/MM/yyyy" mask to its input that is bound to the same column and uses a Parse and a Format event handler before display and send it to the db.
Binding dataNascimentoBinding = new Binding("Text", this.source, "Nascimento", true);
dataNascimentoBinding.Format += new ConvertEventHandler(Util.formatDateConvertEventHandler);
dataNascimentoBinding.Parse += new ConvertEventHandler(Util.parseDateConvertEventHandler);
this.dataNascimentoTxt.DataBindings.Add(dataNascimentoBinding);
public static string convertDateString2DateString(string dateString, string inputFormat, string outputFormat )
{
DateTime date = DateTime.ParseExact(dateString, inputFormat, DateTimeFormatInfo.InvariantInfo);
return String.Format("{0:" + outputFormat + "}", date);
}
public static void formatDateConvertEventHandler(object sender, ConvertEventArgs e)
{
if (e.DesiredType != typeof(string)) return;
if (e.Value.GetType() != typeof(string)) return;
String dateString = (string)e.Value;
e.Value = convertDateString2DateString(dateString, "d/M/yyyy HH:mm:ss", "dd/MM/yyyy");
}
public static void parseDateConvertEventHandler(object sender, ConvertEventArgs e)
{
if (e.DesiredType != typeof(string)) return;
if (e.Value.GetType() != typeof(string)) return;
string value = (string)e.Value;
try
{
e.Value = DateTime.ParseExact(value, "dd/MM/yyyy", DateTimeFormatInfo.InvariantInfo);
}
catch
{
return;
}
}
Like you can see by the code it was expexted that Date coming from SQL would be a DateTime value as is its column, but my eventHandler is receiving a string instead. Likewise, the result date for parse should be a datetime but its a string also.
I'm puzzled dealing with this datetime column.
© Stack Overflow or respective owner