如何使用数字选择控件来增加或减少 datagridview 单元格中的小数位数?

huangapple go评论96阅读模式
英文:

How to Increase or Decrease decimal places in datagridview cells using a NumericUpDown control?

问题

我有一个DataGridView,其中一些行包含文本,而其他行包含大约7位小数的十进制数,我想使用NumericUpDown控件来增加或减少具有数值的单元格的小数部分。

我尝试使用以下代码行的方法,但它没有起作用。

this.DatagridviewDinamic.Columns.Items[i].DefaultCellStyle.Format = "0.00##";

如果你需要进一步的帮助,请告诉我。

英文:

Basically I have a datagridview, some rows contain text and the other rows contain decimal with roughly 7 decimal points, and I would like to use NumericUpDown control to reduce or increase the decimal of cells that have a numerical value.

i tried to use a method with the following line but it didn't work.

this.DatagridviewDinamic.Columns.Items[i].DefaultCellStyle.Format = "0.00##";

答案1

得分: 1

你可以使用标准格式说明符 "N" 和 "F",而不是自定义格式说明符。我经常把它们弄混,但我相信 "N" 将包括组分隔符(例如 12,345),而 "F" 不会(例如 12345)。你可以指定小数位数,例如 "N2" 或 "F2" 来强制保留两位小数,这样你可以像这样做:

this.DatagridviewDinamic.Columns[i].DefaultCellStyle.Format = $"F{myNumericUpDown.Value}";

如果你希望它随着 NumericUpDown 的变化而改变,显然需要处理 ValueChanged 事件并在处理程序中执行这段代码。

我不是100%确定更改 DefaultCellStyle 是否会影响已经在列中的单元格。如果不会,你可能需要循环遍历列中的单元格,并对它们的 Style 属性进行相同的更改。

英文:

You can use the standard format specifiers "N" and "F" instead of that custom format specifier. I often get them mixed up but I believe that "N" will include group separators (e.g. 12,345) and "F" will not (e.g. 12345). You can specify the number of decimal places, e.g. "N2" or "F2" to force two decimal places, so you can do something like this:

this.DatagridviewDinamic.Columns[i].DefaultCellStyle.Format = $"F{myNumericUpDown.Value}";

If you want it to change with the NumericUpDown, you'll obviously need to handle the ValueChanged event and execute that code in the handler.

I'm not 100% sure that changing the DefaultCellStyle will affect cells already in the column. If it doesn't, you may have to loop through the cells in the column and make the same change to their Style properties.

huangapple
  • 本文由 发表于 2023年2月27日 13:34:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/75577043.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定