开发者

How do I resize columns after I populate the dataGridView from a data source in c#?

I can not get this to work. Here is part of my code to give you some idea.

    Scout ScoutInstance = new Scout();
    String sql;
    DataTable table;

    sql = "select * from FD_GROUP";

    table = ScoutInstance.getTableValues(sql);
    dataGridView1.DataSource = table;

    dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;
    dataGridView1.AutoResizeColumns();

    int width = 0;
    foreach (DataGridViewColumn column in dataGridView1.Columns)
       开发者_Go百科 if (column.Visible == true)
        {
            width += column.Width;
            Console.WriteLine("{0}", column.Width);
        }
    Console.WriteLine("{0}", width);

The output I get tells me that both the columns are equal in width (100), however the program itself displays the columns of different widths.


you could try something like this....

private  void setdatagridviewcolumnwidth()
{
   datagridview1.columns[0].width = 100;
   datagridview1.columns[1].width =100;

}

and then put this function after binding the datagridview with datasource(i.e)

table = ScoutInstance.getTableValues(sql);     
dataGridView1.DataSource = table;
setdatagridviewcolumnwidth() //here you will call set widths method


You should have the Grid Layout updated for the right values to show. It won't update before you leave your sub otherwise, since the Layout update is queued. So use :

dataGridView1.UpdateLayout()

After your AutoResizeColumns, and you'll get your values.


About update Layout :

http://msdn.microsoft.com/en-us/library/system.windows.uielement.updatelayout.aspx

"Ensures that all visual child elements of this element are properly updated for layout."

"all computed sizes will be validated."

"You should only call UpdateLayout if you absolutely need updated sizes and positions" ... which is your case.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜