简体   繁体   中英

C# winform create columns in datagridview with observableCollection

I used a simple dataTable to load my data before is this way:

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;

And that worked, but not good enough because i want to update 100x100 matrix of colors fast so i thought about an observable collection.

I have now this code:

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();
}

(grid is my model)

this seems to load all the data but i have no representation to the columns so i have only rows.

How do i specify the amount of columns?

And am i in the right direction?

I used my first lines of code, just added:

            dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.None;

And now it works just fine.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM