C# 如何在DataGridView中使用最大值和最小值格式化带有十进制数字的列?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11229590/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 17:03:51  来源:igfitidea点击:

How to format a column with number decimal with max and min in DataGridView?

c#.netwinformsstringdatagridview

提问by ch2o

I want to format the decimal places displayed and captured in a DataGridView, I have a minimum number of decimal places and a maximum number of decimal places. For example:

我想格式化在 DataGridView 中显示和捕获的小数位,我有最小小数位和最大小数位。例如:

If caught, "120.0" display "120.00"
If caught "120.01" display "120.01"
If caught "120,123" display "120,123"
If caught "120.1234" display "120.1234"
If caught "120.12348" display "120.1235" (round)

In the DataGridView column "txtcDecimal" has the property (from the designer)

在 DataGridView 列中“txtcDecimal”具有属性(来自设计器)

txtcDecimal.DefaultCellStyle.Format = "N2";

txtcDecimal.DefaultCellStyle.Format = "0.00##";  // IS ANSWER. I do not work for an event that interfered

the mask "0.00##" work as "n2" only get 2 decimals which does the correct rounding to two decimal places but just do not like what I need (as I show in the example)

掩码“0.00##”作为“n2”只得到 2 位小数,它可以正确四舍五入到两位小数,但只是不喜欢我需要的(如我在示例中所示)

How I can do it in a simple manner without consuming many resources?

如何在不消耗大量资源的情况下以简单的方式做到这一点?

Thanks harlam357 & Tom Garske

感谢 harlam357 和 Tom Garske

采纳答案by harlam357

To format between 2 and 4 decimal places you can use a custom format string.

要在 2 到 4 个小数位之间设置格式,您可以使用自定义格式字符串。

txtcDecimal.DefaultCellStyle.Format = "0.00##"

To go a bit further...

要走得更远...

public partial class Form1
{
   public Form1()
   {
      InitializeComponent();

      var list = new List<Data>();
      list.Add(new Data { Prop1 = 1, Prop2 = 1.2 });
      list.Add(new Data { Prop1 = 2, Prop2 = 1.234567 });

      dataGridView1.Columns.Add("Prop1", "Prop1");
      dataGridView1.Columns["Prop1"].DataPropertyName = "Prop1";
      dataGridView1.Columns.Add("Prop2", "Prop2");
      dataGridView1.Columns["Prop2"].DataPropertyName = "Prop2";
      dataGridView1.Columns["Prop2"].DefaultCellStyle.Format = "0.00##";
      dataGridView1.DataSource = list;
   }

   class Data
   {
      public int Prop1 { get; set; }
      public double Prop2 { get; set; }
   }
}

回答by Tom

Create a custom formatter.

创建自定义格式化程序。

public class MyFormatProvider : IFormatProvider, ICustomFormatter  
{  
   public object GetFormat(Type formatType)  
   {  
     if (formatType == typeof(ICustomFormatter))  
        return this;  
     else  
        return null;  
   }  

   public string Format(string format, object arg, IFormatProvider formatProvider)  
   {  
     // Check whether this is an appropriate callback               
     if (!this.Equals(formatProvider))  
        return null;  

     //if argument/ value is null we return empty string  
     if (arg == null)  
        return null;  

     string resultString = arg.ToString();  

     //transform resultString any way you want (could do operations based on given format parameter)  

     //return the resultant string  
     return resultString;  
   }  
}  

SOURCE:How to custom format data in datagridview during databinding

来源:如何在数据绑定期间自定义 datagridview 中的数据格式

回答by Tom

To format between 2 and 4 decimal places you can use a custom format string. (As provided by Harlam357)

要在 2 到 4 个小数位之间设置格式,您可以使用自定义格式字符串。(由 Harlam357 提供)

txtcDecimal.DefaultCellStyle.Format = "0.00##"

I verified it with the following simple console application:

我使用以下简单的控制台应用程序验证了它:

        double myDouble = 13.1;
        double myDouble2 = 13.12345;
        Console.WriteLine(myDouble.ToString("0.00##"));
        Console.WriteLine(myDouble2.ToString("0.00##"));
        Console.Read();

The output was:

输出是:

13.10
13.1235

Harlam's answer is clearly correct....

哈拉姆的回答显然是正确的......

UPDATE:This is how I implemented it in forms:

更新:这就是我在表单中实现它的方式:

    public Form1()
    {
        InitializeComponent();

        DataTable dt = new DataTable();
        dt.Columns.Add("a");
        dt.Rows.Add(123.4);
        dt.Rows.Add(123.45);
        dt.Rows.Add(123.456);
        dt.Rows.Add(123.4567);
        dt.Rows.Add(123.45678);
        this.dataGridView1.DataSource = dt;
        this.dataGridView1.CellFormatting += new DataGridViewCellFormattingEventHandler(dataGridView1_CellFormatting);
    }

    void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
    {
        if (e.ColumnIndex == 0 && e.RowIndex != this.dataGridView1.NewRowIndex)
        {
            double d = double.Parse(e.Value.ToString());
            e.Value = d.ToString("0.00##");
        }
    } 

SOURCE:http://social.msdn.microsoft.com/forums/en-US/winformsdatacontrols/thread/95e7e7ef-2e71-412f-abe5-ffbee2c12c18/

来源:http : //social.msdn.microsoft.com/forums/en-US/winformsdatacontrols/thread/95e7e7ef-2e71-412f-abe5-ffbee2c12c18/

OUTPUT:

输出:

Example Output from application

应用程序输出示例