DatagridView: Remove unused space?
Asked Answered
S

10

15

I was wondering whether it is possible to remove the unused space ( the gray space ) of the DataGridView control in C#. I have to make the DataGridView display the white table only.

Any suggestions?

Note: This post originally contained an external image that is no longer valid

Sitdown answered 29/1, 2010 at 15:3 Comment(0)
C
10

Sometimes (especially with winforms) the best way is to hack:

dataGridView1.BackgroundColor = System.Drawing.SystemColors.Control;

I stole it from this post: removing the empty gray space in datagrid in c#

Cynarra answered 6/8, 2012 at 17:27 Comment(1)
This works, but then you still have the border. Any idea how to remove that?Lang
T
7

I have found no simple way to remove the "unused" or gray (BackgroundColor) space. However, an effective solution for me was to hide the borders of the DataGridView and to change its background color to the background of the surrounding control. In essence, the perception is that there is no more unused space.

Here is a snippet in pseudocode:

TableGridView = DataGridView()
TableGridView.Width = 0
TableGridView.Height = 0
TableGridView.AutoSize = true 
TableGridView.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells
TableGridView.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCells
TableGridView.BackgroundColor = SystemColors.ControlLightLight
TableGridView.BorderStyle = BorderStyle.None

I read somewhere that the AutoSize setting is not applicable, however, it did change things for me. This example suggests that the surrounding control has a background color of SystemColors.ControlLightLight, but this can be modified as required.

Please vote this up if it helped you.

Toolis answered 16/5, 2011 at 23:20 Comment(1)
Upvoted, it helped... this was the closest I get so farArlenarlena
A
5

Set the RowsHeaderVisible property to false, you can either do that from the designer, in category Appearence, or from the code :

dataGridView1.RowsHeaderVisible = false;

In order to remove the indicator row on the left side, as for the rest of the grey space, you can try set the aforementionned AutoSizeColumnsMode to Fill, but you will still have the lower part grayed out from lack of rows.

Instead of sizing your cells to fill your grid, you could resize your grid in order to fit around your cells. Whether or not this is an acceptable approach will depend on your intent.

I mean, it's possible that if its just the color that is bothering you, setting the backcolor to white would do the trick.

Ambros answered 29/1, 2010 at 15:36 Comment(1)
So...there is no perfect solution ??Brianabriand
J
3

I believe you want:

myDataGrid.AutoSizeColumnsMode = Fill

EDIT: This just resizes the columns. I'm not sure how you would get rid of row gray space other than resizing the grid's height.

Juetta answered 29/1, 2010 at 15:7 Comment(4)
This won't get rid of all the grey space, just the space to the right of the columns. You'll have to write a handler for the Resize event to size the visible rows to fill the grid if you want that behavior.Logorrhea
With your edit you're incorrect in assuming there is a fill value for AutoSizeRowsMode.Logorrhea
msdn.microsoft.com/en-us/library/…Erelong
@Sid Farkus I just saw the AutoSizeRowsMode property and assumed it did the same things as the AutoSizeColumnsMode property. I had never actually tried the AutoSizeRowsMode. Sorry about that.Juetta
A
1
dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
Attitude answered 25/8, 2010 at 6:11 Comment(2)
Error: Cannot implicitly convert type 'System.Windows.Forms.DataGridViewAutoSizeColumnMode' to 'System.Windows.Forms.DataGridViewAutoSizeColumnsMode'. An explicit conversion exists (are you missing a cast?)Brianabriand
You may add an 's' after Column in your System.Windows.Forms.DataGridViewAutoSizeColumnMode and the problem will be solved :)Aquanaut
B
0

Well, I toiled to find an answer for this before but in the end if you want to mimic an empty DataGridView then the long answer is to create "White" Rectangle objects and use Graphics to fill the whole grid on an overriden OnPaint method.

Bowker answered 19/10, 2012 at 9:38 Comment(0)
U
0

go to the designer:

1) change datagridview background color same as the form color

2) set datagridview "BorderStyle" to None

Underdeveloped answered 1/11, 2018 at 4:24 Comment(0)
R
0

You must set a fixed row-height, then make the height of the DGV to be an exact multiple of the row height, PLUS a couple of pixels.

    DGV1.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.None                                  
    DGV1.RowTemplate.Height = 25                                                               
    DGV1.Height = 252

You will then always show a complete number of rows, plus a bottom tiny margin that will not be gray. To then discover which rows are showing, use:

    Dim firstVisibleRowIndex As Integer = DGV1.FirstDisplayedCell.RowIndex
    Dim lastVisibleRowIndex As Integer = firstVisibleRowIndex + DGV1.DisplayedRowCount(False) - 1
Religion answered 17/7, 2022 at 11:22 Comment(0)
I
0

The problem is old, but still present, so even after all this time another workaround could prove to be useful.

Recently I had the same issue, and did not find a perfect solution, but in my situation, the solution I finally came up with was the least annoying compared to what I found.

Since the auto size is buggy by nature, the only way seemed to be a re-implementation using events.

The question is about C#, and I only have a PowerShell example, because that's what I used when I encountered this issue, but the root cause is in WinForms, and Powershell uses the same thing, through a slightly different API. This means, that the example below shows the major steps for a workaround that can be done using C# as well.

# Import
Add-Type -assembly System.Windows.Forms

# Initialize main form
$window = New-Object System.Windows.Forms.Form
$window.Text ='Test App'

# This is for the window to follow the content
# Although this is technically not relevant, it can limit the options for the workaround because this auto size is not always able to follow the weirdness that's going on
$window.AutoSize = $true

# Create columns
$dataTable = New-Object System.Data.DataTable
$dataTable.Columns.Add("Col1", [System.Type]::GetType("System.Int32"))
$dataTable.Columns.Add("Col2", [System.Type]::GetType("System.Int32"))

# Initialize DataGridView
$grid = New-Object System.Windows.Forms.DataGridView
$grid.DataSource = $dataTable

# These can be anything, but will affect what the sizing needs to be exactly
$grid.ColumnHeadersVisible = $true
$grid.RowHeadersVisible = $true
$grid.BorderStyle = 0

# These are not required, the point is that it works even if the user is poking around
$grid.ReadOnly = $false
$grid.AllowUserToAddRows = $true
$grid.AllowUserToDeleteRows = $true
$grid.AllowUserToOrderColumns = $true
$grid.AllowUserToResizeColumns = $true
$grid.AllowUserToResizeRows = $true

$resizeLogic = {
    # The height and width of the actual grid are available so that the host can be resized to the same size. Note, that this is affected by having the header and any borders
    # See the doc for the magic zeroes: https://learn.microsoft.com/en-us/dotnet/api/system.windows.forms.datagridviewelementstates?view=windowsdesktop-8.0
    $grid.Height = $grid.Rows.GetRowsHeight(0) + $grid.ColumnHeadersHeight
    $grid.Width = $grid.Columns.GetColumnsWidth(0) + $grid.RowHeadersWidth
    # The resize above seems to somehow dodge the main frame's auto-sizing, so this is a gentle reminder.
    # Note, that this limits the Events that can be used as resizing the window triggers some rendering-related events of the grid view
    $window.Height = 0
    $window.Width = 0
}

# Register all events that can impact the size
$grid.Add_RowHeightChanged($resizeLogic)
$grid.Add_ColumnWidthChanged($resizeLogic)
$grid.Add_RowsAdded($resizeLogic)
$grid.Add_RowsRemoved($resizeLogic)
$grid.Add_ColumnAdded($resizeLogic)
$grid.Add_ColumnRemoved($resizeLogic)

# Just some dummy rows
$dataTable.Rows.Add(1)
$dataTable.Rows.Add(2)

# Assemble and show the window
$window.Controls.Add($grid)
$window.ShowDialog()

Note that this is a situational solution, but I liked it compared to making the grid view background "invisible", because this way there is no random dead space, even if it's less visible.

There are two downsides to this though:

  • The resize looks awful (meaning that the content goes black and re-renders cell-by-cell. Deleting multiple rows could be an epilepsy danger zone to be honest)
  • The last row and column cannot be increased in size, because the cursor can only move within the grid view host area (this may be a reason why the unused area is there, and could probably be worked around, but this was enough for me)
Indogermanic answered 14/12, 2023 at 21:9 Comment(0)
D
-2

I use this code for and it works for my if you don't add a button column or image I take it from a site but I don't remember from where :

For Each row As DataGridViewRow In DataGridView1.Rows
If datagrid_limits > newHeight Then
newHeight =newHeight + 40
Else
Exit For
End If
Next
DataGridView1.Height = newHeight
Dirt answered 3/8, 2020 at 21:18 Comment(1)
OP asked for a solution in C# while your answer is VB.Carrageen

© 2022 - 2025 — McMap. All rights reserved.