Search code examples
winformsdatagridviewdatagridviewcolumn

Datagridview Column width


enter image description hereI have problem related to datagridview in Winform.

I have a list of table names in my left panel. When I click on Table I show the table content in right panel. I am showing data in a datagridview by fetching data and assigning datasource to dgv.

I am setting following property to dgv.

dgTemp.Dock = DockStyle.Fill;
dgTemp.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;
dgTemp.AutoSize = true;
dgTemp.DefaultCellStyle.WrapMode = DataGridViewTriState.True;
dgTemp.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCells;
dgTemp.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.DisableResizing;
dgTemp.ReadOnly = true;
dgTemp.AutoGenerateColumns = true;
dgTemp.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
dgTemp.AllowUserToAddRows = false;

My problem is there can be any number of columns in Datasource I am assigning to dgv. So if there are very few number of columns (say 1 or 2) the dgv size stands very small and the empty space on right side give very ugly look. I can't use auto autosizecolumnmode to fill since when there is more columns all columns get shrink and expanding columns dont give me Scroll at bottom

so My requirement is

  1. All space in datagridview should be filled. (should cover all area)
  2. When there is more column, there should appear scroll, so it give better look

are there any events or properties which I can use ??

Thanks in anticipation.


Solution

  • Try this :

    dgTemp.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
    

    Update :

     dataGridView1.FirstDisplayedScrollingRowIndex = 5; //use 5 because you want to start from 5
            //you can have a horizontal scroll bar with this code :
            dataGridView1.FirstDisplayedScrollingColumnIndex = 10; //you can choose every column you wanna start with that column
    

    Update 2 :

    int rows = dataGridView1.Rows.Count;
            int columns = dataGridView1.Columns.Count;
            if (rows < 5 && columns < 10)
            {
                dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
            }
            else
            {
                dataGridView1.FirstDisplayedScrollingRowIndex = 5; //use 5 because you want to start from 5
                //you can have a horizontal scroll bar with this code :
                dataGridView1.FirstDisplayedScrollingColumnIndex = 10; //you can choose every column you wanna start with that column
            }