gpt4 book ai didi

c# - 在 System.Windows.Forms.DataGrid 中设置 double / float /小数精度

转载 作者:行者123 更新时间:2023-11-30 23:20:11 25 4
gpt4 key购买 nike

如何为 System.Windows.Forms.DataGrid 中包含 double 、 float 或小数的数据列设置精度?

对于 DataGridView 有 How to format a column with number decimal with max and min in DataGridView? ,例如。

我希望 0.0100000001 显示为 0.01,例如,这将是小数点后 2 位的精度。我想避免它们看起来像这样,其中 float 和 double 使用科学记数法:

enter image description here

我用来填表的代码是:

var table = new DataTable();
table.Columns.Add("double");
table.Columns.Add("float");
table.Columns.Add("decimal");
table.Columns[0].DataType = typeof(double);
table.Columns[1].DataType = typeof(float);
table.Columns[2].DataType = typeof(decimal);
table.Rows.Add(new object[] { 0.00000000000423, 0.00000000000423, 0.00000000000423 });
dataGrid1.DataSource = table;

注意:我知道 DataGrid 已过时,但我正在处理遗留代码,请不要评论告诉我使用 DataGridView - 它对我没有帮助。

最佳答案

我从@stuartd 的评论中得出了我的解决方案。我需要设置 Formatof the current table style对于数据网格。

/// <summary>
/// Getting and setting the column widths of a DataGrid is not easy at all.
/// This helper class handles it, including saving and restoring from a string.
/// </summary>
static class DataGridColumnWidthExtensions
{
/// Get the current table style.
public static DataGridTableStyle GetCurrentTableStyle(this DataGrid grid)
{
// DataGrid holds the current grid table style into a private field called myGridTable.
// The field points to the "default" table style even if TableStyles is empty. The
// default table style is also private/internal.
// See https://stackoverflow.com/a/39832554/492336 and
// https://referencesource.microsoft.com/#System.Windows.Forms/winforms/Managed/System/WinForms/DataGrid.cs,211.
FieldInfo[] fields = grid.GetType().GetFields(
BindingFlags.NonPublic |
BindingFlags.Instance);

return (DataGridTableStyle)fields.First(item => item.Name == "myGridTable").GetValue(grid);
}
}

然后我们可以迭代 GridColumnStyles 并为每个数字列设置 Format 属性:

var tableStyle = dataGrid1.GetCurrentTableStyle();
for (int ii = 0; ii < table.Columns.Count; ii++)
{
var columnStyle = tableStyle.GridColumnStyles[ii] as DataGridTextBoxColumn;
if (columnStyle == null)
{
// DataGridTextBoxColumn inherits DataGridColumnStyle but in theory
// a column might be of some other type deriving from DataGridColumnStyle.
continue;
}

var columnType = table.Columns[ii].DataType;
if (columnType != typeof(double) && columnType != typeof(float) && columnType != typeof(decimal))
{
// We set the format only for numeric columns.
continue;
}

// 2 digits after the decimal mark.
columnStyle.Format = "N2";
}

关于c# - 在 System.Windows.Forms.DataGrid 中设置 double / float /小数精度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39847445/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com