是否可以将具有1000列的“ System.Data.DataTable”用作“ system.windows.forms.dataGridView”的数据源?

时间:2018-09-27 20:44:24

标签: .net winforms

我可以用1000列填充“ System.Data.DataTable”没有问题(目前没有错误出现),但是当我尝试将其绑定到DataGridView时,会出现以下错误消息:

.NET runtime exception: Sum of the columns' FillWeight values cannot exceed 65535. 

错误出现在这里:

"system.windows.forms.dataGridView".DataSource = "System.Data.DataTable"

仅使用“ system.windows.forms.dataGridView”时,存在相同的问题,但可以使用以下方法解决:

DataGridViewColumn.FillWeight = 1

在创建列并将其添加到DataGridView时。

将DataTable用作dataGridView的数据源时,是否可以解决问题?

1 个答案:

答案 0 :(得分:0)

这是我用来测试DataGridView宽容度的代码。
它将1000 Columns添加到网格和2行数据。
如评论中所述,我也尝试使用2000 Columns来完成任务。即使花很甜蜜的时间才能完成此任务。

请注意,这不受支持
DataGridView不应具有该数量的Columns
而且任何数据模型都不应该具有这种视图。
认为它是对UI对象的压力测试,以查看它在哪里破裂。

int MaxColumns = 1000;

//Create and a DataTable and add [MaxColumns] Columns
DataTable dt = new DataTable("TestTable");
dt.Columns.AddRange(
    Enumerable.Range(0, MaxColumns).Select(idx => 
        new DataColumn("Column" + idx.ToString(), typeof(string))).ToArray());

//Add 2 DataRows with [MaxColumns] values to the DataTable
DataRow row = dt.NewRow();
row.ItemArray = Enumerable.Range(0, MaxColumns).Select(idx => "Value A" + idx.ToString()).ToArray();
dt.Rows.Add(row);
row = dt.NewRow();
row.ItemArray = Enumerable.Range(0, MaxColumns).Select(idx => "Value B" + idx.ToString()).ToArray();
dt.Rows.Add(row);

//Define a CellTemplate for the DataGridViewColumn template
DataGridViewCell ColumnCellTemplate = new DataGridViewTextBoxCell {
    Style = new DataGridViewCellStyle() {
        WrapMode = DataGridViewTriState.False,
        NullValue = string.Empty
    }
};

try
{   //Do not auto generate the columns, otherwise the control will stop the process
    dataGridView1.AutoGenerateColumns = false;

    //Create a [MaxColumns] DataGridViewColumn array
    DataGridViewColumn[] ColumnArray =
        Enumerable.Range(0, MaxColumns).Select(idx =>
            new DataGridViewTextBoxColumn() {
                HeaderText = "Column" + idx.ToString(),
                DataPropertyName = "Column" + idx.ToString(),
                CellTemplate = ColumnCellTemplate,
                AutoSizeMode = DataGridViewAutoSizeColumnMode.None,
                FillWeight = 1,
                DisplayIndex = idx
            }).ToArray();

    dataGridView1.Columns.AddRange(ColumnArray);

   //Bind the DataTable and show the data.
    dataGridView1.DataSource = dt;
}
catch (Exception ex)
{
    Console.WriteLine(ex.Message);
    throw;
}