无法填充DataGridView

3
我正在从DataTable中填充DataGridView,但是遇到以下错误:

至少有一列DataGridView控件没有单元格模板

private void PopulateGridView(DataTable dt)
        {

            if (dt != null)
            {
                dataGridView1.Columns.Clear();
                dataGridView1.DataSource = null;

                foreach (DataColumn col in dt.Columns)
                {
                    //Declare the bound field and allocate memory for the bound field.
                    DataGridViewColumn datacolumn = new DataGridViewColumn();

                    //Initalize the DataField value.
                    datacolumn.DataPropertyName = col.ColumnName;

                    datacolumn.Name = col.ColumnName;

                    //Initialize the HeaderText field value.
                    datacolumn.HeaderText = col.ColumnName;


                    //Add the newly created bound field to the GridView.
                    this.dataGridView1.Columns.Add(datacolumn); // ** Error **
            }

                //Initialize the DataSource
                this.dataGridView1.DataSource = dt;
            }

2
仅仅这样做“this.dataGridView1.DataSource = dt;”有什么问题吗? - CatchingMonkey
4个回答

7
你看到的错误是因为你添加了没有分配单元格模板的基础列类型 DataGridViewColumn 。如果DataGridView尝试为此列分配新单元格,它将不知道该怎么做。
你可以选择定义列类型,或将列的单元格模板设置为单元格。
DataGridViewTextBoxColumn col = new DataGridViewTextBoxColumn();
datagridview1.Columns.Add(col);

或者

DataGridViewColumn col= new DataGridViewColumn();
DataGridViewTextBoxCell cell = new DataGridViewTextBoxCell();

col.CellTemplate = cell;
datagridview1.Columns.Add(col);

有几种可用的列类型。

然而,您可能希望让列自动生成。将DataGridView属性AutoGenerateColumns设置为true(默认值),当您分配数据源时,将创建列。

以编程方式添加列通常很有用(例如添加一个复选框列以允许选择行),但在这种情况下,您不需要这样做。


3

就像ASPMapper在原问题下面的评论中说的那样,只需设置即可。甚至无需预先清除列:

private void PopulateGridView(DataTable dt)
{
  dataGridView1.DataSource = dt;
  // notice if your DataTable is null, it simply clears the DataGridView control
}

2

您的代码崩溃是因为DataGridViewColumn没有提供单元格模板...

也许您想使用其中之一?(而不是基本的DataGridViewColumn

DataGridViewButtonColumn
DataGridViewCheckBoxColumn
DataGridViewComboBoxColumn
DataGridViewImageColumn
DataGridViewLinkColumn
DataGridViewTextBoxColumn

另一方面,DataGridView能够在运行时自动创建列,当提供新的数据源时...


1
private void PopulateGridView(DataTable dt)
{


    if (dt != null)
    {
        dataGridView1.Columns.Clear();
        dataGridView1.DataSource = null;

        dataGridView1.AutoGenerateColumns = true;

        this.dataGridView1.DataSource = dt;
            }
        }
}
}

正在为我完成工作。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接