【问题标题】:How to fix length of characters in DataGrid cells如何修复 DataGrid 单元格中的字符长度
【发布时间】:2011-11-09 08:40:01
【问题描述】:

我有一个带有列的数据网格,ID 的值类似于 1,2,3,4,5....10,11,12,13... 我希望所有值的长度为 2,这意味着我希望值为 01,02,03....10,11,12... 怎么做?

编辑 我正在使用 Winforms。

编辑

    if (dg.Columns[e.ColumnIndex].Name == "Id")
    {
        try
        {
            //e.Value = String.Format("{0:00.0}", e.Value);

            DataGridViewCellStyle ca = new DataGridViewCellStyle();
            ca.ForeColor = System.Drawing.Color.Red;
            ca.Format = "d2";

            dg.Columns[e.ColumnIndex].DefaultCellStyle = ca;
            e.FormattingApplied = true;
        }
        catch (FormatException)
        {
            e.FormattingApplied = false;
        }
    }

我可以在这里更改背景颜色和前景色,但无论我做什么,文本格式都保持不变。我什至尝试使用 String.Format (注释行),但它也不起作用。 我也试过你的代码,它不起作用。不知道怎么回事。

【问题讨论】:

    标签: .net winforms c#-4.0 datagrid


    【解决方案1】:

    (数据网格视图)

    对于DataGridView,尝试设置DefaultCellStyleFormat 属性,如this

    this.dataGridView1.Columns["COLUMN_NAME"].DefaultCellStyle.Format = "d2";
    

    (WinForms DataGrid 答案)

    在 WinForms 中,MSDN 说 DataGridTextBoxColumn 上有一个 Format 属性;我不经常使用 WinForms 来验证那是正确的列类型。


    (网络表单答案)

    您可以在列上使用DataFormatString 属性:

    DataFormatString="{0:D2}"
    

    【讨论】:

    • 添加了 WinForms(潜在)答案
    • 在 msdn 中,他们用 Datagrid 给出了解释,这在 Visual Studio 2010 中不可用(由 DatagridView 代替)。因为我对.net 很陌生,所以很难破解解决方案。还是谢谢
    • 添加了一个潜在的 DataGridView 答案
    【解决方案2】:

    使用 ToString("00") 格式化字符串效果很好。

    【讨论】:

      猜你喜欢
      • 2019-12-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-22
      • 2014-10-26
      • 2018-09-11
      • 2014-09-22
      • 1970-01-01
      相关资源
      最近更新 更多