【问题标题】:Simplest way of programmatically creating a DataGridView with X columns by Y rows以编程方式创建 X 列 X 行的 DataGridView 的最简单方法
【发布时间】:2012-08-04 04:54:44
【问题描述】:

在 C# Winforms 中,我想使用 DataGridView 作为一个简单的小部件来存储要显示给用户的信息。为此,我想创建一个 5x10 单元格的表格。

经过一些研究,解决方案往往允许一次只添加一行或一列。我希望整个网格一开始就立即创建,所以我可以开始用数据填充它,就像使用标准 C# 2D 数组一样。

解决这个问题的最简单方法是什么?函数头可能如下所示:

createCells(DataGridView dgv, int cols, int rows) {}

如果需要,以后可以快速且易于将列和行更改为更大或更小的数字。

【问题讨论】:

    标签: c# winforms datagridview


    【解决方案1】:

    顺便说一下,可能会出现如下错误:

    列的 FillWeight 值之和不能超过 65535

    为避免这种情况,请将AutoGenerateColumns 属性设置为false,并将FillWeight 设置为1 生成的每一列:

    dgv.AutoGenerateColumns = false;
    for (int i = 1; i <= columns; i++)
    {
        dgv.Columns.Add("col" + i, "column " + i);
        dgv.Columns[i - 1].FillWeight = 1;
    }
    for (int j = 0; j < rows; j++)
        dgv.Rows.Add();
    

    【讨论】:

    • 然后说我是否想在此之后创建一个较小的表并将其替换为旧表?有没有办法删除所有单元格或类似的?
    • 啊哈发现了如何:dgv.Rows.Clear(); dgv.Columns.Clear();。再次感谢您的帮助!
    【解决方案2】:

    您可以通过这种方式使用 for 循环:

        private DataGridView DGV_Creation(DataGridView dgv, int columns, int rows)
        {
            for (int i = 1; i <= columns; i++)
            {
                dgv.Columns.Add("col" + i, "column " + i);
            }
            for (int j = 0; j < rows; j++)
            {
                dgv.Rows.Add();
            }
            return dgv;
        }
    

    调用它:

    this.dataGridView1 = DGV_Creation(dataGridView1, 5, 10); // 5 columns, 10 rows (empty rows)
    

    或:

        private void DGV_Creation(ref DataGridView dgv, int columns, int rows)
        {
            for (int i = 1; i <= columns; i++)
                dgv.Columns.Add("col" + i, "column " + i);
            for (int j = 0; j < rows; j++)
                dgv.Rows.Add();
        }
    

    调用它:

    DGV_Creation(ref this.dataGridView1, 5, 10); //5 columns, 10 rows (empty rows)
    

    【讨论】:

    • 太好了,谢谢。立即完成这个技巧,相当快(10000x20 单元格只需几秒钟),并且代码比我担心的要少。我可能很快就会打勾。
    • 我添加了一些不同的解决方案,通过使用 ref 关键字(无需将 dataGridView 对象传回(如 dgv = ...),但正是您想要的方式
    • 谢谢,我认为根本不需要 ref,因为它已经由 ref 发送了?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-08
    • 1970-01-01
    • 1970-01-01
    • 2015-03-22
    • 2015-05-02
    • 1970-01-01
    相关资源
    最近更新 更多