格式化未绑定数据源的DataGridView列

时间:2009-07-22 13:38:58

标签: c# winforms

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

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

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

List<BorderFlowHistoryElement> clusterHistory

包含thise元素的列表,应该在我的DataGridView中显示。我将列表绑定到Grid的DataSource:

dataGridViewCluster.DataSource = clusterHistory;

现在DataGridView显示列表。现在我想格式化显示double值的列以显示5位数。我尝试过:

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

但这对列没有影响。谁知道,我怎么做对了? 此外,我希望将列宽调整为最适合最大条目的范围。

提前致谢, 弗兰克

1 个答案:

答案 0 :(得分: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;}
    }
}

我希望以某种方式有所帮助。如您所见,您也可以进行自动调整大小。