Dominik Lorke
Dominik Lorke

Reputation: 51

How to convert datetime in dataGridView?

I have column in my database with datetime. I want bind to DataGridView, but I have problem with DateTime format, when I am binding data to table.

I read about change format datatime like this

mydatagridView.Columns[0].dataGridViewCellStyle.Format = "dd/MM/yyyy";

but it doesn't work.

This is the code with bind data from the database.

Connect();

SQLiteCommand cmdDataBase = new SQLiteCommand("select date from database", Connect());
try
{
    SQLiteDataAdapter sda = new SQLiteDataAdapter();
    sda.SelectCommand = cmdDataBase;
    DataTable dbdataset = new DataTable();

    sda.Fill(dbdataset);

    BindingSource bSource = new BindingSource();

    bSource.DataSource = dbdataset;
    dataGridView1.DataSource = bSource;
    sda.Update(dbdataset);


}
catch (Exception ex)
{
    MessageBox.Show(ex.Message);
}

Upvotes: 0

Views: 924

Answers (1)

Innat3
Innat3

Reputation: 3576

I believe the problem lies in the fact that the column type of the first column in the DataTable is probably not defined as DateTime, therefore it doesn't recognize the formatting pattern.

In order to update the column type, the DataTable must be edited, however once the DataTable has been filled with data, you are not allowed to edit the column, and you won't be, since you are doing it dynamically with the .Fill() method.

You could however create a clone of the DataTable structure and apply the desired column modifications, and afterwards copy the the data from one to another.

SQLiteDataAdapter sda = new SQLiteDataAdapter();
sda.SelectCommand = cmdDataBase;
DataTable dbdataset = new DataTable();
sda.Fill(dbdataset);

DataTable dbdatasetclone = dbdataset.Clone();
dbdatasetclone.Columns[0].DataType = typeof(DateTime);           
foreach (DataRow row in dbdataset.Rows)
{
    dbdatasetclone.ImportRow(row);
}

BindingSource bSource = new BindingSource();
bSource.DataSource = dbdatasetclone;
dataGridView1.DataSource = bSource;
dataGridView1.Columns[0].DefaultCellStyle.Format = "dd/MM/yyyy";

Upvotes: 3

Related Questions