【问题标题】:Formating DataGridView Columns for an unbound data source为未绑定的数据源格式化 DataGridView 列
【发布时间】:2009-07-22 13:38:57
【问题描述】:

我正在努力使用 WinForms DataGridView。我有一个类,我将其用作要显示的元素:

public class BorderFlowHistoryElement
{
    public string nodeTitles { get; set; }
    public double borderFlowRatio { get; set; }
    ...
}

我创建了这些元素的列表:

List<BorderFlowHistoryElement> clusterHistory

其中包含应显示在我的 DataGridView 中的 thise 元素列表。我在 Grid 的 DataSource 处绑定了列表:

dataGridViewCluster.DataSource = clusterHistory;

现在 DataGridView 显示列表。现在我想将显示双精度值的列格式化为显示 5 位数字。我试过了:

dataGridViewCluster.Columns[1].DefaultCellStyle.Format = "n5";

但这对列没有影响。任何人都知道,我该怎么做? 此外,我想调整列宽以最适合最大条目。

提前致谢, 弗兰克

【问题讨论】:

  • 您是在寻找总位数还是精度?您正在指定精度,因此如果您有一个数字 1234 并且您使用 N5,您将得到 1,234.00000。这就是你想要的吗?
  • 我正在寻找精度。例如 3.1415672467234823499821 应该变成 3.14157

标签: c# winforms


【解决方案1】:

我已经复制了你所做的,我没有任何问题。您是否验证了您的数据以确保您确实可以获得您想要的结果?

这是我做的仅供参考:

private void button1_Click(object sender, EventArgs e)
    {
        IList<BorderFlowHistoryElement> clusterHistory = FillClusterHistory();

        dataGridView1.DataSource = clusterHistory;

        dataGridView1.Columns[1].DefaultCellStyle.Format = "n5";

        dataGridView1.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCells);

    }

    private static IList<BorderFlowHistoryElement> FillClusterHistory()
    {
        IList<BorderFlowHistoryElement> clusterHistory = new   List<BorderFlowHistoryElement>();


        for(int i = 5000; i < 5020; i++)
        {
            BorderFlowHistoryElement element = new BorderFlowHistoryElement();

            element.nodeTitles = Guid.NewGuid().ToString();

            element.borderFlowRatio = i * 3.3.1415672467234823499821D;

            clusterHistory.Add(element);
        }

        return clusterHistory;
    }
}

public class BorderFlowHistoryElement
{
    private string _NodeTitles;
    private double _BorderFlowRatio;

    public string nodeTitles
    {
        get { return _NodeTitles; }
        set { _NodeTitles = value;}
    }

    public double borderFlowRatio
    {
        get { return _BorderFlowRatio; }
        set { _BorderFlowRatio = value;}
    }
}

我希望这会有所帮助。如您所见,您也可以进行自动调整大小。

【讨论】:

  • 它对我帮助很大:它表明我的格式化代码是正确的,错误需要在其他地方。我发现了问题:我首先尝试在 VS-Designer 中创建 ColumnTemplates。它没有用,但我错过了将它们全部删除(我认为这不会是一个问题,因为在将我的列表绑定到数据源时它们被覆盖了)。但似乎它们的纯粹存在阻止了我以编程方式形成网格。此外,自动尺寸的东西正是我想要的。非常感谢您的努力!
猜你喜欢
  • 1970-01-01
  • 2017-12-26
  • 2018-06-28
  • 2014-09-15
  • 2019-03-14
  • 1970-01-01
  • 2017-05-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多