Harald
Harald

Reputation: 889

Date formatting WPF datagrid

I´ve got a special problem, that first seems very easy but I don´t know any solution. At the moment I programm a C#-WPF-Application that makes it possible to save bookings. A booking also has a date, which I take from a calender. I save the booking to my Sql-Express Database and the value of a date is "DD.MM.YYYY", the datatype is date.

Now, I load the data into a datagrid in my application:

    public DataSet SaveDataToDataSet(DataSet dataset)
    {

        string connectionString = "Data Source=.\\SQLEXPRESS;AttachDbFilename=C:\\Users\\Harald\\Desktop\\Farmer´s Calc\\Programmierung\\WPF\\Finanz_WPF\\Finanz_WPF\\FarmersCalc.mdf;Integrated Security=True;User Instance=True";
        string query = "select bezeichnung 'Bezeichnung', einausgaben 'Einnahmen-Ausgaben',  kostenstelle 'Kostenstelle',  datum 'Buchungsdatum', betrag 'Betrag', details 'Details' from Buchung";
        using (SqlConnection connection =
            new SqlConnection(connectionString))
        {
            SqlDataAdapter adapter = new SqlDataAdapter();
            adapter.SelectCommand = new SqlCommand(
                query, connection);

            adapter.Fill(dataset);
            return dataset;

        }
    }

Strangely, the date column in the DataGrid has the format "DD.MM.YYYY HH:MM:SS", but I only want "DD.MM.YYYY"! What I need to say is, that I don´t have Columns defined, I make it with AutoGenerateColumns=true. Does anybody know a solution for that?

Upvotes: 1

Views: 7653

Answers (2)

Adam Barney
Adam Barney

Reputation: 2387

The "date" Sql type ends up being a DateTime in your dataset, which is why you're getting the time as well. You'll need to define columns and specify formatting on your datagrid.

EDIT: I was mistaken about not being able to format this when auto generating columns. As the other answer here mentions, this question: Need to format dates in dynamically built WPF DataGrid addresses some ways to accomplish this.

Upvotes: 2

Jay
Jay

Reputation: 6017

Check this out:

Need to format dates in dynamically built WPF DataGrid

It involves using string formatting in your Grid resources.

There are answers in there that don't involve defining the columns... including handling it in the event for auto-generating columns.

private void ResultsDataGrid_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
{
    if (e.PropertyType == typeof(DateTime))
    {
        DataGridTextColumn dataGridTextColumn = e.Column as DataGridTextColumn;
        if (dataGridTextColumn != null)
        {
            dataGridTextColumn.Binding.StringFormat = "{0:d}";
        }
    }
}

Upvotes: 5

Related Questions