DataGridView decimal value formatting: kosher way

元气小坏坏 提交于 2019-12-11 16:34:00

问题


I need to display decimal values in DataGridView

        if (dgvClients.SelectedRows.Count != 0)
        {
            DataGridViewRow row = dgvClients.SelectedRows[0];

            row.Cells["NetAccountValue"].Value = info.DecimalValue;
        }

I need to format value up to given digits after decimal separator.

The problem is that cell Value property stores reference to decimal in my case. When displayed decimal.ToString() is called and default decimal.ToString() produces unformatted string with lots of digits.

One way is to create string and use String.FormatString() to achieve desired formatting and feed it Value instead of decimal.

Is there some other way?


回答1:


Using code you can set the DataGridView.DefaultCellStyle property.

You can also do this in the designer by:

  1. Right clicking your DGV and select Edit Columns. The Edit Columns dialog appears.
  2. Select your column on the left side of the dialog and click the DefaultCellStyle property field to bring up the CellStyle Builder.
  3. In the Builder dialog click Format which brings up the Format String Dialog.
  4. Make your selections in this dialog (select Numeric type, which allows specifying number of decimals to display) and save your changes.



回答2:


i found this solution simply.i have searched along two days,found it finally. -your db column type must be Money or number,double,single. -Update datagridview event "CellFormatting" as below code.

private void dataGridView2_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
   {
       if (this.dataGridView2.Columns[e.ColumnIndex].Name == "Aidat")
       {
          string deger=(string)e.Value;
          deger = String.Format("{0:0.00}", deger);
       }
   }


来源:https://stackoverflow.com/questions/1889775/datagridview-decimal-value-formatting-kosher-way

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!