开发者

fit dataGridView size to row's and columns's total size

I want to make a dataGridView's size to fit the columns and rows total size. About total height, I managed to fit it to columns's height like that:

const int datagridLines = 30;
s.Height = dataGridView2.Columns[0].HeaderCell.Size.Height;
for (byte i = 0; i < datagridLines; i++)
{
  dataGridView2.Rows.Add();
  s.Height += dataGridView2.Rows[i].Height;
}
dataGridView2.ClientSize = s;

I tried some things to also fit the width bu开发者_如何转开发t no luck. Any suggestions?

Thanks.


This should work:

int height = 0;
foreach (DataGridViewRow row in dataGridView1.Rows) {
    height += row.Height;
}
height += dataGridView1.ColumnHeadersHeight;

int width = 0;
foreach (DataGridViewColumn col in dataGridView1.Columns) {
    width += col.Width;
}
width += dataGridView1.RowHeadersWidth;

dataGridView1.ClientSize = new Size(width + 2, height + 2);

The + 2 to the width and height values are a fudge factor to account for the width of the DataGridView's interior elements. I recall seeing code somewhere that will allow you to get this value without the hard coded numbers but I can't find it now.


GetRowsHeight and GetColumnsWidth methods of Rows and Columns collections should give you what you need in an effortless way:

var totalHeight = dataGridView2.Rows.GetRowsHeight(DataGridViewElementStates.None);
var totalWidth = dataGridView2.Columns.GetColumnsWidth(DataGridViewElementStates.None);


A bit more complete version:

dataGridView.Height = dataGridView.Rows.GetRowsHeight(DataGridViewElementStates.None) + dataGridView.ColumnHeadersHeight + 2;

dataGridView.Width = dataGridView.Columns.GetColumnsWidth(DataGridViewElementStates.None) + dataGridView.RowHeadersWidth + 2;


You will need to use the properties of the DataGridViewRow collection and DataGridViewColumn collection to do this.

Try the approach similar to the one used in this:

how to increase rows size in DataGridView


It's a tad late and in visual basic, but this worked for me in case someone else finds this thread. I'm using a docked datagridview in a tableLayoutPanel, which automatically resizes when the form is resized. It doesn't shrink the form. I just start the form small. Rows could be added using the same technique.

Private Sub setFormWidth()
        Dim iTotalWidth As Integer = 0 '884
        Dim iDisplayedWidth As Integer = 0
        Dim r As Rectangle
        For Each c As DataGridViewColumn In dgv_EmpList.Columns
            If c.Visible Then
                iTotalWidth += c.Width
                r = dgv_EmpList.GetColumnDisplayRectangle(c.Index, True)
                iDisplayedWidth += r.Width
            End If
        Next
        Me.Width += (iTotalWidth - iDisplayedWidth)
    End Sub
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜