user3085995
user3085995

Reputation: 453

format column (value) of datatable dynamically

Is it possible to format a datatable column value at runtime?

I'm trying to show the date inside my DateTime column as below,

foreach (DataColumn c in ds.Tables[0].Columns)
{
    if (c.DataType == typeof(DateTime))
    {
        string.Format("MM/dd/yyyy", c);
    }
}

but getting full date with time..

EDIT :

till now, i'm upto this,..

 foreach (DataRow dr in ds.Tables[0].Rows)
     {
     foreach (DataColumn dc in ds.Tables[0].Columns)
        {
         if (dc.DataType == typeof(DateTime))
            {
             if (!String.IsNullOrEmpty(Convert.ToString(dr[dc])))
              {
               //string s = dr[dc].ToString();
               //dr[dc] = s.Substring(0, s.IndexOf(' '));
               //dr[dc] = Convert.ToDateTime(dr[dc]).ToShortDateString();
               dr[dc] = Convert.ToDateTime(dr[dc]).ToString("MM/dd/yyyy");
              }
             }
         }
       }

still not able to get the desired result

Upvotes: 4

Views: 6463

Answers (1)

user3085995
user3085995

Reputation: 453

got the solution as below,..

                    DataTable dtCloned = ds.Tables[0].Clone();
                    foreach (DataColumn c in ds.Tables[0].Columns)
                    {
                        if (c.DataType == typeof(DateTime))
                        {
                            dtCloned.Columns[c.ColumnName].DataType = typeof(string);
                            colNames.Add(c.ColumnName);
                        }
                    }
                    foreach (DataRow row in ds.Tables[0].Rows)
                    {
                        dtCloned.ImportRow(row);
                    }

                    foreach (DataRow dr in dtCloned.Rows)
                    {
                        foreach (DataColumn dc in dtCloned.Columns)
                        {
                            if (colNames.Contains(dc.ColumnName))
                            {
                                string dt = Convert.ToString(dr[dc]);
                                if (!String.IsNullOrEmpty(dt))
                                {
                                    DateTime date = DateTime.ParseExact(dt.Substring(0, dt.IndexOf(' ')), "M/d/yyyy", System.Globalization.CultureInfo.InvariantCulture);
                                    dr[dc] = date.ToString("MM/dd/yyyy");
                                }
                            }
                        }
                    }

Upvotes: 2

Related Questions