473,320 Members | 1,794 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,320 software developers and data experts.

Datagridview - Change yyyymmdd to mm/dd/yyyy

rob
I have a class that among others exposes a string property "Date". The
date in this property is stored in the form yyyymmdd. Now I do the
following

1) Generate a DataGridViewTextBoxColumn column for that property
2) Add the column to the datagridview
3) Populate a BindingSource by adding all instances of the above
mentioned class.
4) Assign the BindingSource to the datagridview's DataSource property

At this point the column with the date shows the date in the form
yyyymmdd. I now try to change that by reading the cell's value, convert
it to mm/dd/yyyy and set the new cell value. Unfortunately, this has no
effect at all. Even in debug mode when I change the value manually in
the watch window it refuses the new value without any exception.

I guess the first question is if it is possible at all to change the
value of a cell without(!) propegating that change back to the data
source. If it is possible how is it done? If it is not possible then
how can I achive my goal?

Thanks

Jan 5 '06 #1
10 26881
rob wrote:
I have a class that among others exposes a string property "Date". The
date in this property is stored in the form yyyymmdd. Now I do the
following

1) Generate a DataGridViewTextBoxColumn column for that property
2) Add the column to the datagridview
3) Populate a BindingSource by adding all instances of the above
mentioned class.
4) Assign the BindingSource to the datagridview's DataSource property

At this point the column with the date shows the date in the form
yyyymmdd. I now try to change that by reading the cell's value, convert
it to mm/dd/yyyy and set the new cell value. Unfortunately, this has no
effect at all. Even in debug mode when I change the value manually in
the watch window it refuses the new value without any exception.

I guess the first question is if it is possible at all to change the
value of a cell without(!) propegating that change back to the data
source. If it is possible how is it done? If it is not possible then
how can I achive my goal?

Thanks


Have you tried to set the DataFormatString to {0:MM/dd/yyyy} ? (Not that
this specific date format makes any sense to me - I'd take the original
ISO Date format over that any day...)
Jan 5 '06 #2
DataFormatString sounds like a property of the DataGrid from ASP.NET, not
WinForm's DataGridView.

Use code like so:

Dim colShipDate As New DataGridViewTextBoxColumn()

colShipDate.SortMode = DataGridViewColumnSortMode.Automatic
colShipDate.AutoSizeMode = DataGridViewAutoSizeColumnMode.ColumnHeader
colShipDate.DataPropertyName = "ShipDate"
colShipDate.HeaderText = "Ship Date"
colShipDate.Name = "ShipDate"
colShipDate.ReadOnly = True

Dim cellStyle As DataGridViewCellStyle = New DataGridViewCellStyle()
cellStyle.BackColor = Color.Thistle
cellStyle.Format = "MM/dd/yyyy"

colShipDate.DefaultCellStyle = cellStyle

DataGridView1.Columns.Add(colShipDate)

Greg
"john smith" <jo**@smith.com> wrote in message
news:uM*************@TK2MSFTNGP09.phx.gbl...
rob wrote:
I have a class that among others exposes a string property "Date". The
date in this property is stored in the form yyyymmdd. Now I do the
following

1) Generate a DataGridViewTextBoxColumn column for that property
2) Add the column to the datagridview
3) Populate a BindingSource by adding all instances of the above
mentioned class.
4) Assign the BindingSource to the datagridview's DataSource property

At this point the column with the date shows the date in the form
yyyymmdd. I now try to change that by reading the cell's value, convert
it to mm/dd/yyyy and set the new cell value. Unfortunately, this has no
effect at all. Even in debug mode when I change the value manually in
the watch window it refuses the new value without any exception.

I guess the first question is if it is possible at all to change the
value of a cell without(!) propegating that change back to the data
source. If it is possible how is it done? If it is not possible then
how can I achive my goal?

Thanks


Have you tried to set the DataFormatString to {0:MM/dd/yyyy} ? (Not that
this specific date format makes any sense to me - I'd take the original
ISO Date format over that any day...)

Jan 5 '06 #3
Hi,

"rob" <rm*******@yahoo.com> wrote in message
news:11**********************@g14g2000cwa.googlegr oups.com...
I have a class that among others exposes a string property "Date". The
date in this property is stored in the form yyyymmdd. Now I do the
following

1) Generate a DataGridViewTextBoxColumn column for that property
2) Add the column to the datagridview
3) Populate a BindingSource by adding all instances of the above
mentioned class.
4) Assign the BindingSource to the datagridview's DataSource property

At this point the column with the date shows the date in the form
yyyymmdd. I now try to change that by reading the cell's value, convert
it to mm/dd/yyyy and set the new cell value. Unfortunately, this has no
effect at all. Even in debug mode when I change the value manually in
the watch window it refuses the new value without any exception.
You can use the DataGridView's CellParsing and CellFormating events:

using System.Globalization;

private void dataGridView_CellFormatting(object sender,
DataGridViewCellFormattingEventArgs e)
{
if (dataGridView.Columns[e.ColumnIndex].DataPropertyName == "Date" )
{
DateTime dt = DateTime.ParseExact((string)e.Value, "yyyymmdd",
DateTimeFormatInfo.InvariantInfo);

e.Value = dt.ToString("mm/dd/yyyy",
DateTimeFormatInfo.InvariantInfo); //*

e.FormattingApplied = true;
}
}

private void dataGridView_CellParsing(object sender,
DataGridViewCellParsingEventArgs e)
{
if (dataGridView.Columns[e.ColumnIndex].DataPropertyName == "Date")
{
DateTime dt = DateTime.ParseExact((string)e.Value, "mm/dd/yyyy",
DateTimeFormatInfo.InvariantInfo); //*

e.Value = dt.ToString("yyyymmdd",
DateTimeFormatInfo.InvariantInfo);

e.ParsingApplied = true;
}
}

(*) you could also use "d" and DateTimeFormatInfo.CurrentInfo to show the
date in the short-date-format for the users current culture.

HTH,
Greetings

I guess the first question is if it is possible at all to change the
value of a cell without(!) propegating that change back to the data
source. If it is possible how is it done? If it is not possible then
how can I achive my goal?

Thanks

Jan 5 '06 #4
rob
Great, it works now. There are two problems left, though:

1) The glyph is not shown anymore on any of the colums when I set the
datasource property of my datagridview to the bindingsource. This works
fine when I create rows on my datagridview and manually set each cell's
content.

2) This approach is much slower (factor 1.5) then by setting the
content of each cell manually. Is there a way to improve this?

Thanks,

Jan 6 '06 #5
Greg Burns wrote:
DataFormatString sounds like a property of the DataGrid from ASP.NET, not
WinForm's DataGridView.


Yes it is. Somehow my brain only seems to have registered 3 words of
what he said: GridView, Date and Format (I was very tired). The solution
works, but indeed just in ASP.Net...
Jan 6 '06 #6
Hi,

"rob" <rm*******@yahoo.com> wrote in message
news:11**********************@g44g2000cwa.googlegr oups.com...
Great, it works now. There are two problems left, though:

1) The glyph is not shown anymore on any of the colums when I set the
datasource property of my datagridview to the bindingsource. This works
fine when I create rows on my datagridview and manually set each cell's
content.
If you mean the sorting glyph, then that's because the list the
BindingSource is using doesn't support sorting. In case you didn't assign a
list to the BindingSource.DataSource then the default list is a
BindingList<T> which doesn't support sorting.

You could use a SortableBindingList<T> posted at the end of this message.
Create a Data Source (Menu-Data) for your class (eg. Customer), then from
the Data Sources window drag it on the Form. Then from code in form_load
assign the actual list to be used, example:

private void Form_Load(...)
{
someBindingSource.DataSource = new SortableBindingList<Customer>();
someBindingSource.Add( new Customer("fkdsf") );
someBindingSource.Add( new Customer("fdsf") );
}

But sorting the 'Date' column correctly while being a string would be hard
and require more code, so if it is possible use a DateTime for your Date
column.

2) This approach is much slower (factor 1.5) then by setting the
content of each cell manually. Is there a way to improve this?
Not sure about this, probely some databinding overhead, gonna have a look
later, but i doubt i'll find something.

HTH,
Greetings

The code for SortableBindingList<T> is at
http://msdn.microsoft.com/library/de...ms02182005.asp ,
but because some parts are missing, i pasted the complete code here:

using System;
using System.Reflection;
using System.Collections.Generic;
using System.Text;
using System.ComponentModel;

namespace test1.CellFormat
{
public class SortableBindingList<T> : BindingList<T>
{
private PropertyDescriptor sortProp = null;
private ListSortDirection sortDir =
ListSortDirection.Ascending;

private bool isSorted = false;

protected override bool SupportsSortingCore
{
get { return true; }
}

protected override void ApplySortCore(PropertyDescriptor property,
ListSortDirection direction)
{
PropertyComparer<T> pc =
new PropertyComparer<T>(property, direction);

((List<T>)this.Items).Sort(pc);

isSorted = true;
sortProp = property;
sortDir = direction;

// Let bound controls know they should refresh their views
this.OnListChanged(new
ListChangedEventArgs(ListChangedType.Reset, -1));
}

protected override bool IsSortedCore
{
get { return isSorted; }
}

protected override void RemoveSortCore()
{
// can't unsort
}

protected override PropertyDescriptor SortPropertyCore
{
get { return sortProp; }
}

protected override ListSortDirection SortDirectionCore
{
get { return sortDir; }
}
}

public class PropertyComparer<T> : System.Collections.Generic.IComparer<T>
{
// The following code contains code implemented by Rockford Lhotka:
//
http://msdn.microsoft.com/library/de...et01272004.asp

private PropertyDescriptor _property;
private ListSortDirection _direction;

public PropertyComparer(PropertyDescriptor property, ListSortDirection
direction)
{
_property = property;
_direction = direction;
}

#region IComparer<T>

public int Compare(T xWord, T yWord)
{
// Get property values
object xValue = GetPropertyValue(xWord, _property.Name);
object yValue = GetPropertyValue(yWord, _property.Name);

// Determine sort order
if (_direction == ListSortDirection.Ascending)
{
return CompareAscending(xValue, yValue);
}
else
{
return CompareDescending(xValue, yValue);
}
}

public bool Equals(T xWord, T yWord)
{
return xWord.Equals(yWord);
}

public int GetHashCode(T obj)
{
return obj.GetHashCode();
}

#endregion

// Compare two property values of any type
private int CompareAscending(object xValue, object yValue)
{
int result;

// If values implement IComparer
if (xValue is IComparable)
{
result = ((IComparable)xValue).CompareTo(yValue);
}
// If values don't implement IComparer but are equivalent
else if (xValue.Equals(yValue))
{
result = 0;
}
// Values don't implement IComparer and are not equivalent, so compare
as string values
else result = xValue.ToString().CompareTo(yValue.ToString());

// Return result
return result;
}

private int CompareDescending(object xValue, object yValue)
{
// Return result adjusted for ascending or descending sort order ie
// multiplied by 1 for ascending or -1 for descending
return CompareAscending(xValue, yValue) * -1;
}

private object GetPropertyValue(T value, string property)
{
// Get property
PropertyInfo propertyInfo = value.GetType().GetProperty(property);

// Return value
return propertyInfo.GetValue(value, null);
}
}
}

Thanks,

Jan 6 '06 #7
Rob,

It is easy to do, however you have to be wise.

Make from the String property a DateTime value.

With that is everything done by Microsoft what you ask.

(And for that is not a small amount of code that they made).

Cor
Jan 6 '06 #8
Hi,

"Cor Ligthert [MVP]" <no************@planet.nl> wrote in message
news:e2*************@tk2msftngp13.phx.gbl...
Rob,

It is easy to do, however you have to be wise.

Make from the String property a DateTime value.

With that is everything done by Microsoft what you ask.
Not if he wants to use databinding, when you have custom objects then
sorting is not supported by default (even if the property is DateTime)
because the default list used for binding is BindingList<T> which does not
support sorting. That's why he needs SortableBindingList<T>.

Greetings


(And for that is not a small amount of code that they made).

Cor

Jan 7 '06 #9
rob
Cor,

Do you mean I should change the property of the class that exposes the
date which is used for the data binding? If so the problem is that I
can't change this because other components already expect the format we
currently have. If not then can you please elaborate?

Thanks

Jan 7 '06 #10
Rob,

Using string for a DateTime is for me from the time from the punchcard. In
the Microsoft Database server all datetimes are in ticks (diferent methods
for short Time and DateTime). As well is a DateTime in Net the datetime in
ticks (other format). Which means that in can be represented in any way you
want and even standard based on your culture settings. The different formats
are almost seamless converted.

For from from String to Date is
DateTime.parse
Convert.DateTiem
CDate

For from Date to String is the overloaded ToString with the IFormatProvider

For bounding with non complex datacontrols are the binding events

http://www.vb-tips.com/default.aspx?...9-4deb7fa4a0b8

And there is even much more by instance the way to interact with the
database server

http://www.vb-tips.com/default.aspx?...6-7139b8970071

So if there is so much done by Microsoft to help you to do it correct, what
is it than not to use it?

I hope that this gives an idea

Cor
Jan 7 '06 #11

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

10
by: =?Utf-8?B?TWlrZQ==?= | last post by:
I have a string variable containing a date formatted as YYYYMMDD For example - Dim x as string = "20070314" If I try to perform a type conversion as follows I get an error: Dim y as Date =...
2
by: DavidOwens | last post by:
SELECT DISTINCTROW Format(PERIOD.START_DT,"mmmm yyyy") AS MonthYear, SALES.PERIOD_ID, Sum(SALES.SALES) AS SumOfSALES, Sum(SALES.SALES_UNITS) AS SumOfSALES_UNITS, Sum(SALES.SALES_VALUE) AS...
17
by: rdraider | last post by:
I can't seem to find a method of converting a CHAR(8) column in the form of YYYYMMDD to an actual date such as mm/dd/yyyy Can anyone point me in the right direction? Thanks
1
by: rdraider | last post by:
I can't seem to find a way to convert an INT type in the form of YYYYMMDD to an actual date form of mm/dd/yyyy Can anyone pointt me in the right direction? Thanks
1
by: =?Utf-8?B?dHZpbg==?= | last post by:
Hi everyone i want to format YYYYMMDD to MM/DD/YYYY by vb.net is there any format function for this process in vb.net thanks for your help
3
by: Bface | last post by:
Hi all, Hope everyone had a good holiday. I am having a difficult time changing the date format of a field from Excel. I have never had this problem before. I link the excel spreadsheet to my DB,...
2
by: stainless | last post by:
I know this is probably simple but I cannot find a method of converting a date string into a format that matches the DatePicker format in C# eg string "20080131" converted to "31 January 2008" ...
0
by: modolamara | last post by:
Hi people, im importing a date column from a mysql database to a datagridview but it automatically changes the date format from 'YYYY-MM-DD' (Mysql format) to 'MM/DD/YYYY' since the user has...
0
by: priyamtheone | last post by:
I'm trying to make a datagridview column to act like a datetimepicker column (C#.Net 2005). These are the behaviours that the dgv should have: 1) Initially all the cells of the dtp column should be...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.