编程语言
首页 > 编程语言> > C#-水平​​滚动条消失,设置最后一个要填充的列大小

C#-水平​​滚动条消失,设置最后一个要填充的列大小

作者:互联网

我有一个datagridview有4列.我想要:

>显示每个单元格中的所有文本(我不想看到任何被“ …”截断的文本)
>最后一栏填满所有剩余空间
>水平和垂直滚动条.

使用此代码:

  dataGridView.ScrollBars = ScrollBars.Both;
  Grid_NonAnatObj.AutoResizeColumns();
  GridCol_Visibility.Width = 30;

我看到每个单元格中的所有文本都没有截断,并且看到水平和垂直滚动条.
当我尝试添加此代码时

  Grid_NonAnatObj.Columns[3].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;

为了满足2.,水平滚动条消失了.
我怎么解决这个问题?

解决方法:

这是一个hack-around,但这是我能做的最好的事情,可以尽可能地模拟所需的结果.

  1. to display all the texts inside every cell (I don’t want to see any texts truncated with “…”)

至少,这意味着每列都应将AutoSizeMode设置为DisplayedCells.这将为您进行拟合,因此您不必猜测:“ 30宽度足够吗?也许35才可以以防万一……”.从本质上讲,它还使您的色谱柱具有最小的宽度感.

但是,如果您的值都很小,而现在您在最后一列的右侧有一个丑陋的未使用区域,该怎么办?

  1. that the last column fills all the remaining space

有条件的最后一组列AutoSizeMode可以解决此问题.

  1. the Horizontal and Vertical scrollbar.

这有点让步,但是当最后一栏设置为填充时,您将不需要水平栏.将其设置为DisplayedCells时,这些列要么完全适合您的宽度,要么大于您的宽度,在这种情况下,条会显示出来.

CODEZ PLZ:
为了通过调整大小来保持这种行为的一致性,我在dgv Resize事件中实现了它.

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;
  }
}

问题:这很好用,但是还需要在窗体构造函数中触发才能从一开始就正确显示.

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";
}

编辑:如果您的单元格是可编辑的,并且可能输入的数据太长,可能导致省略号…

private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
  this.dataGridView1_Resize(this.dataGridView1, EventArgs.Empty);
}

标签:autosize,datagridview,scrollbar,c,winforms
来源: https://codeday.me/bug/20191120/2047242.html