简体   繁体   中英

C# How to Change DataTable Column Dimensions in A DataGridView

I am trying to set the width and height of the cells in a Column in a DataTable/DataGridView.

I understand from the internet it is done like this:

grid.Columns[0].Width = 10;

however this gives me an outOfRange Exception. If I try to find it by name then i get a null reference.

        DataTable dt = new DataTable();
        dt.Columns.Add("Date");
        dt.Columns.Add("Smørrebrød");
        dt.Columns.Add("Minismørrebrød");
        dt.Columns.Add("Buffet");
        dt.Columns.Add("Daily Orders");

        DataGridView grid = new DataGridView();
        grid.DataSource = dt;
        grid.Width = 1000;
        grid.Columns[0].Width = 10;
        window.Controls.Add(grid);

Can someone illustrate how this is properly done?

Change the width set operations as shown below

DataTable dt = new DataTable();
dt.Columns.Add("Date");
dt.Columns.Add("Smørrebrød");
dt.Columns.Add("Minismørrebrød");
dt.Columns.Add("Buffet");
dt.Columns.Add("Daily Orders");

DataGridView grid = new DataGridView();
grid.DataSource = dt;
grid.Width = 1000;
Controls.Add(grid);
grid.Columns[0].Width = 10;

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