简体   繁体   中英

Horizontal Scroll Bar on DataGridView

Is there a way to have the horizontal scroll bar while having the AutoSizeMode for the column set to fill?

When the width of content in the rows exceed the width of the DataGridView, I want to enable the horizontal scroll bar. Not sure how to do this. With the research I have done, I found that using the "AllCell" option in the AutoSizeMode would enable the scroll bar, however, I want the rows to fill the DataGridView.

You can't have both behaviors natively.
You will have to code it using DataGridViewColumn.MinimumWidth property.
Here is an example using DataGridView 's CellValueChanged event (but you will certainly have to adapt it to your specific case) :

private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
    dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;
    foreach (DataGridViewColumn column in dataGridView1.Columns)
        column.MinimumWidth = column.Width;
    dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
}

Be careful, this can be very time consuming if you have lots of rows in your datagrid.

There's a simple way around it, although it obviously isn't ideal:

  • add an empty collumn with AutoSizeMode set to Fill at the end
  • and set HeaderText of the last column to an empty string (which I obviousy forgot to do in my demo...)

This way it (almost) appears as if the AutoSizeMode of the 2nd column is set to FIll.

Here, Column1 and Column2 have AutoSizeMode set to DisplayedCells, Column3 to Fill:

在此处输入图片说明在此处输入图片说明

This is a really old post, but thought I would add to it. If you are not bothered by setting AutoSizeMode to Fill.

Set the AutoSizeMode of the problematic column to AllCells.

This will resize the column header and force it to go out of the visible area thus displaying the horizontal scrollbar.

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