horizontal scrollbar disappear setting the last column size to fill

半腔热情 提交于 2019-11-28 02:06:26

It's a hack-around, but this was the best I could do to mock as closely the results you wanted.

  1. to display all the texts inside every cell (I don't want to see any texts truncated with "...")

At the very minimum, this means each column should have AutoSizeMode set to DisplayedCells. This will do the fitting for you so you don't have to guess, "Is 30 width enough? Maybe 35 just in case...". Essentially it also gives your columns a mimicked minimum width feel.

But what if your values are all small and now you have that ugly unused area on the right-hand side of the last column?

  1. that the last column fills all the remaining space

A conditional set of the last columns AutoSizeMode to Fill can fix this.

  1. the Horizontal and Vertical scrollbar.

It's a little give-and-take, but when the last column is set to fill, you'll have no need of the horizontal bar. When it's set to DisplayedCells, the columns either exactly fit your width or they are larger than your width, in which case the bar will show.

CODEZ PLZ: To keep this behavior consistent through resizes, I implemented it in the dgv Resize event.

private void dataGridView1_Resize(object sender, EventArgs e)
{
  int width = this.dataGridView1.RowHeadersWidth;

  foreach (DataGridViewColumn col in this.dataGridView1.Columns)
  {
    col.AutoSizeMode = DataGridViewAutoSizeColumnMode.DisplayedCells;
    width += col.Width;
  }

  if (width < this.dataGridView1.Width)
  {
    this.dataGridView1.Columns[this.dataGridView1.Columns.Count - 1].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
  }
}

Problem: This works great, but also needs to be triggered in the form constructor to display correctly from the start.

public Form1()
{
  this.InitializeComponent();

  this.Examples = new BindingList<Example>() 
  {
    new Example() { First = "Foo", Last = "Bar", Test = "Small" },
    new Example() { First = "My", Last = "Example", Test = "You." }
  };

  this.dataGridView1.DataSource = this.Examples;

  this.Visible = true; // Do this or during the initial resize, the columns will still be 100 width.
  this.dataGridView1_Resize(this.dataGridView1, EventArgs.Empty); // Invoke our changes.
  //this.Examples[0].Test = "ReallyBigExampleOfTextForMySmallLittleColumnToDisplayButResizeToTheRescue";
}

Edit: If your cells are editable and there's a chance long data may be entered causing the dreaded ellipsis...

private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
  this.dataGridView1_Resize(this.dataGridView1, EventArgs.Empty);
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!