Format in DataGridViewColumn seems not to work

Answered
0
1

Hi,

 

I uploaded a sample project, where I used the VS2022 Designer to set the Format of a TextBoxColumn. This creates code that creates a defaultStyle object.

I’m setting some Data through a dataTable as the DataSource

Am I wrong to think that the datagrid should now show the data always with 2 decimals and a currency symbol and also reformat the numbers if I edit them? Because it’s not doing any of that.

What am I doing wrong?

(...)
            this.NumbersColumn.DataPropertyName = "Numbers";
            dataGridViewCellStyle1.Format = "C2";
            dataGridViewCellStyle1.NullValue = null;
            this.NumbersColumn.DefaultCellStyle = dataGridViewCellStyle1;
            this.NumbersColumn.HeaderText = "Numbers";
            this.NumbersColumn.Name = "NumbersColumn";
(...)

 

(constructor)
            _dataTable = new DataTable();
            _dataTable.Columns.Add("Text");
            _dataTable.Columns.Add("Numbers");
            _dataTable.Rows.Add("eins", 1.01);
            _dataTable.Rows.Add("zwo", 3.99);

            dataGridView1.DataSource = _dataTable;
            _dataTable.AcceptChanges();

 

  • You must to post comments
Best Answer
1
1

Hi Sascha,

The reason why formatting wouldn’t work is because you didn’t specify the value type to the “Numbers” column, so it defaults to a string, and Strings don’t support formatting.

So the solution is that you have to specify the Column type :

_dataTable.Colums.Add(“Numbers”, typeof(double));

Best,
Alaa

  • You must to post comments
Showing 1 result
Your Answer

Please first to submit.