Datatable cell vale change not working

Bikramj 21 Reputation points
2021-07-12T06:15:24.657+00:00

Hi ,

I want to change the date format for all the rows for a speciific column in a datatable but when i am assigning the changed value to it its not reflecting.

foreach (DataRow dr in dBTable.Rows)
{
dr[4] = Convert.ToDateTime(dr[4]).ToString("dd-MMM-yy");
}

Can anyone please help?

Thanks

C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,348 questions
{count} votes

Accepted answer
  1. Karen Payne MVP 35,196 Reputation points
    2021-07-12T10:57:48.667+00:00

    Hello,

    A DataTable is for storing data, not for changing the format in the case of a DateTime, no different from storing a DateTime in a database table.

    If displaying in say a DataGridView, set the format.

    113769-f1.png

    Code

    public Form1()  
    {  
        InitializeComponent();  
          
        Shown += OnShown;  
        dataGridView1.AutoGenerateColumns = false;  
    }  
      
    private void OnShown(object sender, EventArgs e)  
    {  
        var table = new DataTable();  
      
        table.Columns.Add(new DataColumn("SomeDate", typeof(DateTime)));  
      
        table.Rows.Add(new DateTime(2021,1,1));  
        table.Rows.Add(new DateTime(2021,2,1));  
        table.Rows.Add(new DateTime(2021,3,1));  
      
        dataGridView1.DataSource = table;  
    }  
    

    Then we can do the following

    private void button1_Click(object sender, EventArgs e)  
    {  
        var table = (DataTable) dataGridView1.DataSource;  
      
        StringBuilder sb = new StringBuilder();  
        foreach (DataRow row in table.Rows)  
        {  
            sb.AppendLine(row.Field<DateTime>("SomeDate")  
                .ToString("dd-MMM-yy"));  
        }  
      
        MessageBox.Show(sb.ToString());  
    }  
    

    Or

    var datesFormatted = ((DataTable) dataGridView1.DataSource)  
        .AsEnumerable()  
        .Select(row => row.Field<DateTime>("SomeDate").ToString("dd-MMM-yy"))  
        .ToArray();  
      
    MessageBox.Show(string.Join("\n",datesFormatted));  
    

    113893-f2.png

    0 comments No comments

0 additional answers

Sort by: Most helpful