iJade
iJade

Reputation: 23801

Unable to modify dataset

Here is a piece of my c# code

if (dsResult != null && dsResult.Tables[0].Rows.Count > 0)
{
    foreach (DataRow dr in dsResult.Tables[0].Rows)
    {
        dr["Date"] = Convert.ToDateTime(dr["Date"]).ToString("yyyy-MM-dd");
    }
}
dsResult.Tables[0].AcceptChanges();

What i'm trying to do is that the dataset has a Date in format d/m/yyyy and i'm trying to modify the data to format yyyy-MM-dd but my dataset is not getting updated.

Upvotes: 1

Views: 324

Answers (1)

Mike Perrenoud
Mike Perrenoud

Reputation: 67898

The way the date is stored and the way it's displayed are two very different things. The reason it shows as 1/7/2013 00:00:00 AM in the DataTable for example is because it's showing the default display for the DateTime based on your culture settings.

However, this is often not how you want it displayed, so there are a number of ways to skin this cat, but I'll give you a couple. First and foremost, you could simply change the culture of your application so that it's displayed the way you want by default.

CultureInfo culture = (CultureInfo)CultureInfo.CurrentCulture.Clone();
culture.DateTimeFormat.ShortDatePattern = "yyyy-MM-dd";
Thread.CurrentThread.CurrentCulture = culture;

Now, when you display DateTime values you're going to get that culture by default when you issue for example:

var dt = new DateTime();
dt.ToShortDateString(); // here is where the culture is used

You may also find that you have a specific spot in your application where you need to display it a certain way, well you can do that to:

var dt = new DateTime();
dt.ToString("dd-MM-yyyy"); // custom formatting on the fly

So, in short, you don't need to change it in the DataTable. Regardless of how it's displayed the value is the same.

Upvotes: 2

Related Questions