Search code examples
c#wpfdatagrid

WPF C# .NET 4.7.2 / Index datagridcolumn and change format


So I just filled a WPF datagrid with sql server data with this code:

string strSqlHomeView = "select * from MyTable"
string connetionString = @"Data Source=MyDataSource;Initial Catalog=MyDb;Integrated Security=SSPI";
SqlConnection cnn = new SqlConnection(connetionString);
SqlDataAdapter sqlDA1 = new SqlDataAdapter(strSQL, cnn);
System.Data.DataTable Dt = new System.Data.DataTable();
sqlDA1.Fill(Dt);
MyDatagrid.ItemsSource = Dt.DefaultView;
cnn.Close();

But as it's data from SQL, it seems I cannot directly change the format from XAML, so I guess I need to index the column from the code behind. I just want to round 2 after comma. In Winform, with a datagridview I would do like this:

dataGridView1.Columns["MyColumn"].DefaultCellStyle.Format = "0.##";

For those who use to play with Python Dataframe or C# winform datagridview, do you know how to set up things from column to column like an iloc function or an indexing. Since the Microsoft doc isn't vey explicit about that, it's not that straightforward to find something relevant on the internet because each example has its own particularities.

Anyway, thanks in advance for helping


Solution

  • If your columns are auto-generated then you can handle AutoGeneratingColumn and set the format this way:

    MyDatagrid.AutoGeneratingColumn += MyDatagrid_AutoGeneratingColumn
    ...
    private void MyDatagrid_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
    {
        if(e.PropertyName == "MyColumn")
        {
            DataGridTextColumn col = e.Column as DataGridTextColumn;
            col.Binding = new Binding(e.PropertyName) { StringFormat = "0.##" };
        }
    }