简体   繁体   中英

How to set default column size(height,width) of columns of Data Grid View in C#

I have a data table. After creating this table, I use data grid view to show data by simply using the code:

mydataGridView.DataSource = myTable;

By this, dataGridView creates columns and rows according to data from myTable automatically. However, when I do that, I can't set the width of columns in dataGridView. What should i do to fix this?

I don't use any code for setting size. My dataGridView auto generates the columns and i want to set the size of these auto generated columns.

There's a gotcha in this one:

MyGrid.TableStyles(0).GridColumnStyles(2).width = SomeValue;

Pretty sure you always get at least one TableStyle and one ColumnStyle on instantiating the grid. After that you have to create and add a column style for each column. Same for Rowstyle if you need it as well.

If you style a grid from VS, set number of columns, only one columnstyle will be defined and it will be used for all columns from 0 onwards. If you wantedf to make column 3 different then you have to set up columns 0,1 and 2. Then 3 and unless you want columns 4 .. n to be the same as three, a column 4 one to be used from then onwards.

Caught me out as well.

So you'll need code as far as I'm aware, you can make it generic though if you can pass in a list of style properties you want to use.

好吧……在DataGrid的xaml中,您有ColumnWidth参数可以做到这一点。

你可以试试:

dataGridView.Columns[i].Width = 60;

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