【问题标题】:C# winform create columns in datagridview with observableCollectionC# winform 使用 observableCollection 在 datagridview 中创建列
【发布时间】:2016-04-12 06:43:02
【问题描述】:

我之前用一个简单的dataTable来加载我的数据是这样的:

DataTable dt = new DataTable("grid");
//split array to width X height dataTable

// create columns
for (int i = 0; i < width; i++)
{
    dt.Columns.Add();
}

for (int i = 0; i < height; i++)
{
    // create a DataRow using .NewRow()
    DataRow row = dt.NewRow();
    // iterate over all columns to fill the row
    for (int j = 0; j < width; j++)
    {
        row[j] = grid.Cells[j + (width * i)].State.ToString();
    }
    // add the current row to the DataTable
    dt.Rows.Add(row);
}
dataGridView1.DataSource = dt;

这很有效,但还不够好,因为我想快速更新 100x100 的颜色矩阵,所以我想到了一个可观察的集合。

我现在有这个代码:

ObservableCollection<String> data = new ObservableCollection<String>();
dataGridView1.DataSource = new BindingSource { DataSource = data };

for (int i = 0; i < grid.Cells.Length; i++)
{              
   data[i] = grid.Cells[i].State.ToString();
}

(网格是我的模型)

这似乎加载了所有数据,但我没有对列的表示,所以我只有行。

如何指定列数?

我的方向是否正确?

【问题讨论】:

标签: c# winforms datagridview observablecollection


【解决方案1】:

我使用了我的第一行代码,只是添加了:

            dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.None;

现在它工作得很好。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-09-06
    • 1970-01-01
    • 1970-01-01
    • 2013-11-27
    • 2016-05-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多