How can I make a transparent tabPage? - c#

How can I make a transparent tabPage? I found solutions like set both Form's BackColor and TransparencyKey to a color like Color.LimeGreen or override OnPaintBackground with a empty method but TabPage doesn't have neither TransparencyKeyproperty norOnPaintBackground` method. How can I do that?

TabControl is a native Windows component, it always draws the tab pages opaque with no built-in support for transparency. Solving this requires a little helping of out-of-the-box thinking, a tab control with transparent tab pages simply devolves to just the tabstrip being visible. All you have to do is use panels to host the controls that are now on the tab pages and make the correct one visible with the SelectedIndexChanged event.
Best to stick this in a derived class so you can still use the tab control normally at design time. Add a new class to your project and paste the code shown below. Compile. Drop the new control from the top of the toolbox onto the form, replacing the existing one.
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
class TransparentTabControl : TabControl {
private List<Panel> pages = new List<Panel>();
public void MakeTransparent() {
if (TabCount == 0) throw new InvalidOperationException();
var height = GetTabRect(0).Bottom;
// Move controls to panels
for (int tab = 0; tab < TabCount; ++tab) {
var page = new Panel {
Left = this.Left, Top = this.Top + height,
Width = this.Width, Height = this.Height - height,
BackColor = Color.Transparent,
Visible = tab == this.SelectedIndex
};
for (int ix = TabPages[tab].Controls.Count - 1; ix >= 0; --ix) {
TabPages[tab].Controls[ix].Parent = page;
}
pages.Add(page);
this.Parent.Controls.Add(page);
}
this.Height = height /* + 1 */;
}
protected override void OnSelectedIndexChanged(EventArgs e) {
base.OnSelectedIndexChanged(e);
for (int tab = 0; tab < pages.Count; ++tab) {
pages[tab].Visible = tab == SelectedIndex;
}
}
protected override void Dispose(bool disposing) {
if (disposing) foreach (var page in pages) page.Dispose();
base.Dispose(disposing);
}
}
Call the MakeTransparent() method in the form's Load event handler:
private void Form1_Load(object sender, EventArgs e) {
transparentTabControl1.MakeTransparent();
}

Related

Dynamically resize TabControl and Form width to the number of TabPages

I have a windows form with a TabControl and a ListView.
When I run the application, I want the Width of the TabControl to increase/decrease to show all the TabPages without horizontal scrollbar and have the Form resize it's Width accordingly, to insure that the TabControl and ListView are visible.
A screenshot is below.
To auto-size a TabControl to the size of its Headers, you need to calculate the width of the text of each Header. It's simpler in case the TabControl.SizeMode is set to Fixed, since you can set the ItemSize.Width and all Headers will have the same width.
If the TabControl.SizeMode is set to the default Normal, you have to measure the Text of each Header, adding 1px for the Border (2px if it's the second TabPage - small bug in the base Control).
In the first case, the size of the TabControl is:
tabControl1.Width = tabControl1.TabPages.Count * (tabControl1.ItemSize.Width + 1);
in the second case, measure the text of each Header using TextRendrer.MeasureText:
private int MeasureTabPagesWidth(TabControl tc)
{
if (tc.TabPages.Count == 0) return tc.Width;
int newWidth = 0;
int border = tc.TabPages.Count == 2 ? 2 : 1;
var flags = TextFormatFlags.LeftAndRightPadding;
using (var g = tc.CreateGraphics()) {
foreach (TabPage tab in tc.TabPages) {
newWidth += TextRenderer.MeasureText(g, tab.Text, tc.Font,
new Size(int.MaxValue, tc.Font.Height + 4), flags).Width + border;
}
}
return newWidth;
}
Setup the Layout:
Add a TableLayoutPanel to your Form, with one Row and two Columns (i.e., remove one Row)
Add the TabControl to the Cell on the left and the ListBox to the other Cell.
Set both Cells's style to AutoSize (after you have added your Controls).
Set the TableLayoutPanel to: AutoSize = true, AutoSizeMode = GrowAndShrink
Set the Form to auto-size in the same way
Set the Form's MinimumSize and MaximumSize. The former is usually set to the design size, the latter is up to you; you could use the current Screen WorkingArea as reference.
Calculate the new Width of the TabControl when the Form is created or loaded (i.e., in its Constructor or OnLoad() or Form.Load), so the Form will auto-size to the size of the TableLayoutPanel, whici in turn auto-sizes to the size of its child Controls.
Now you can add or remove TabPages at run-time and the Form will auto-size to the width you calculate in the TabControl.ControlAdded and TabControl.ControlRemoved event handlers (also checking whether the Control added is of Type TabPage).
Example:
The MeasureTabPagesWidth() method is the one shown above.
The TableLayoutPanel is named tlp1
The TabControl is named tabControl1
The Buttons used in the visual example have names that define their role.
public partial class AutoSizeForm : Form
{
public AutoSizeForm()
{
InitializeComponent();
tabControl1.Width = MeasureTabPagesWidth(tabControl1);
}
private void tabControl1_ControlAdded(object sender, ControlEventArgs e)
{
// Event notified after the TabPage has been added
if (e.Control is TabPage) {
tabControl1.Width = MeasureTabPagesWidth(tabControl1);
}
}
private void tabControl1_ControlRemoved(object sender, ControlEventArgs e)
{
if (e.Control is TabPage) {
// Use deferred execution, since the TabPage is removed after
// the event handler method completes.
BeginInvoke(new Action(()=> tabControl1.Width = MeasureTabPagesWidth(tabControl1)));
}
}
private void btnAddPage_Click(object sender, EventArgs e)
{
tabControl1.TabPages.Add(new TabPage("New TabpPage Text"));
}
private void btnRemovePage_Click(object sender, EventArgs e)
{
if (tabControl1.TabPages.Count > 0) {
tabControl1.TabPages.RemoveAt(tabControl1.TabPages.Count - 1);
}
}
private void btnAddCtlToTLP_Click(object sender, EventArgs e)
{
tlp1.ColumnCount += 1;
tlp1.ColumnStyles.Add(new ColumnStyle(SizeType.AutoSize));
var mc = new MonthCalendar();
tlp1.SetColumn(mc, tlp1.ColumnCount - 1);
tlp1.Controls.Add(mc);
}
}
This is how it works:
Tested in Windows 7, since this appears to be the System in use
Sample Project:
Sample Project on Google Drive (.Net Framework 4.8 - C# 7.3)
Rebuild the Solution before running
Starting out with that form, I'm going to add 8 tabs at run-time, calculate width of the text in the tabs + padding size x2 (both sides of the tabs) and then resize controls as needed.
public Form1()
{
InitializeComponent();
//Clear our default tabs.
tabControl1.TabPages.Clear();
//Add more tabs than would be visible by default
for (int i=1;i<=8;i++)
{
tabControl1.TabPages.Add("Tab " + i.ToString());
}
ResizeTabControl();
ResizeListViewControl();
ResizeForm();
}
void ResizeTabControl()
{
int tabCount = tabControl1.TabCount;
float length = 0;
using (Graphics g = CreateGraphics())
{
//Iterate through the tabs and get the length of the text.
for (int i = 0; i <= tabCount - 1; i++)
length += g.MeasureString(tabControl1.TabPages[i].Text, tabControl1.Font).Width;
}
//Resize the tab control where X is the length of all text in the tabs plus padding x 2 x total tabs.
tabControl1.Size = new Size(Convert.ToInt32(length) + (tabCount * 2 * tabControl1.Padding.X), tabControl1.Width);
}
void ResizeListViewControl()
{
//Move listview 10 pixels away from tabcontrol's edge
listView1.Location = new Point(tabControl1.Location.X + tabControl1.Width + 10, listView1.Location.Y);
}
void ResizeForm()
{
//Resize form to accomodate changes.
this.Width = listView1.Location.X + listView1.Width + 20;
}
After it's all said and done, this is what it looks like:
And with 20 tabs, because why not.

AutoScroll problem when using Left Dock - C# Telerik Winforms

Here is my code:
RadScrollablePanel panel = new RadScrollablePanel() { AutoScroll = true, Dock = DockStyle.Fill};
pnlclp.PanelContainer.Controls.Add(panel);
foreach (var date in dates)
panel.Controls.Add(new ucDetails() { Dock = DockStyle.Left });
I'm adding some controls inside a RadScrollablePanel and then adding it into a PanelContainer.
Everything works great. If I add so many controls inside the RadScrollablePanel which is not visible in first look, the scroll bar will be shown as well.
But If I change the DockStyle.Left to DockStyle.Right in foreach loop, after loading the controls, it will not show the scroll bar and it is strange and I can not find any reason or solution to solve this issue.
I even try to change the RightToLeft property of RadScrollablePanel. but no success :(
Any suggestion?
Following the provided information, I have prepared a sample project to test the behaior in RadScrollablePanel.
I have logged it in our feedback portal by creating a public thread. You can track its progress, subscribe for status changes and add your comments on the following link: https://feedback.telerik.com/winforms/1453253-radscrollablepanel-missing-scrollbar-when-there-is-no-enough-space-to-display-the-content-controls
I hope this information helps.
To work around this problem of the standard Microsoft WinForms Panel, I can suggest docking all the UserControls to the Left and use an empty Panel that occupies all the available space on the left of the form, so exactly the same behavior as all UserControls are docked to the Right. When the size of the form is changed adjust the width of the empty panel. The described approach is illustrated with the code below:
public partial class Form1 : Form
{
UserControl1[] userControls;
RadScrollablePanel parentPanel;
Panel spacePanel;
public Form1()
{
InitializeComponent();
new Telerik.WinControls.RadControlSpy.RadControlSpyForm().Show();
}
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
this.parentPanel = new RadScrollablePanel();
this.parentPanel.Dock = DockStyle.Fill;
this.parentPanel.BackColor = Color.Yellow;
this.Controls.Add(this.parentPanel);
this.parentPanel.AutoScroll = true;
int count = 10;
this.userControls = new UserControl1[count];
for (int i = 0; i < count; i++)
{
this.userControls[i] =
new UserControl1()
{
Dock = DockStyle.Left,
BackColor = Color.FromKnownColor((KnownColor)(i + 50))
};
this.parentPanel.Controls.Add(this.userControls[i]);
}
this.spacePanel = new Panel();
this.spacePanel.Dock = DockStyle.Left;
this.parentPanel.Controls.Add(this.spacePanel);
}
protected override void OnSizeChanged(EventArgs e)
{
base.OnSizeChanged(e);
if (this.spacePanel != null)
{
int lastPanelWidth = this.parentPanel.Width;
foreach (Control control in this.parentPanel.PanelContainer.Controls)
{
if (control.Dock == DockStyle.Left && control != this.spacePanel)
{
lastPanelWidth -= control.Width;
}
}
if (lastPanelWidth < 0)
{
lastPanelWidth = 0;
}
this.spacePanel.Width = lastPanelWidth;
}
}
}

TabPage title alignment being wrong after drag'n'dropping

I have the class that extends System.Windows.Forms.TabControl and had implemented drag'n'drop mechanism for its TabPages as following:
#region Overriden base methods
protected override void OnDragOver(DragEventArgs e)
{
if (PointedTabPage == null) return;
e.Effect = DragDropEffects.Move;
var dragTab = e.Data.GetData(typeof (ManagedTabPage)) as ManagedTabPage;
if (dragTab == null) return;
int dropIndex = TabPages.IndexOf(PointedTabPage);
int dragIndex = TabPages.IndexOf(dragTab);
if (dragIndex == dropIndex) return;
var modifiedTabPages = new List<ManagedTabPage>(from ManagedTabPage tabPage in TabPages
where TabPages.IndexOf(tabPage) != dragIndex
select TabPages[TabPages.IndexOf(tabPage)] as ManagedTabPage);
modifiedTabPages.Insert(dropIndex, dragTab);
for (byte i = 0; i < TabPages.Count; ++i)
{
var managedTabPage = TabPages[i] as ManagedTabPage;
if (managedTabPage != null && managedTabPage.Uid == modifiedTabPages[i].Uid)
continue;
TabPages[i] = modifiedTabPages[i];
}
SelectedTab = dragTab;
}
protected override void OnMouseDown(MouseEventArgs e)
{
try
{
switch (e.Button)
{
case MouseButtons.Left:
DoDragDrop(PointedTabPage, DragDropEffects.Move);
break;
case MouseButtons.Middle:
CloseTab(PointedTabPage);
break;
}
}
catch (InvalidOperationException)
{
}
finally
{
TabPages.Insert(0, String.Empty);
TabPages.RemoveAt(0);
}
}
#endregion
Nota bene that in the finally clause of OnMouseDown method there are 2 lines for workarounding the
problem: for some reason w/o these lines after drag'n'dropping any of TabPages alignment of their titles is being wrong:
What should I do to correct this behavior without this smelly workaround? Maybe sending some Windows messages could do the trick?
Thanks a lot for any suggestions.
Edit 1. Code of ManagedTabPage is 100% unimportant (it's just extends TabPage with some specific properties).
PointedTabPage is unimportant too, but this is it:
return (from ManagedTabPage tabPage in TabPages
let tabPageIndex = TabPages.IndexOf(tabPage)
where GetTabRect(tabPageIndex).Contains(PointToClient(Cursor.Position))
select TabPages[tabPageIndex]).Single() as ManagedTabPage;
I'm trying to achieve fully-centered alignment of labels. You see, labels on the screenshot didn't centered horizontally?
I can't do much with the posted code. Let's take a completely different tack and create a tabcontrol that supports dragging a tabpage with the mouse. Add a new class to your project and paste this code:
using System;
using System.Drawing;
using System.Windows.Forms;
class TabControlEx : TabControl {
private Point downPos;
private Form draggingHost;
private Rectangle draggingBounds;
private Point draggingPos;
public TabControlEx() {
this.SetStyle(ControlStyles.UserMouse, true);
}
}
The usage of the variable becomes clear later. First thing we need is to get mouse events from the TabControl so we can see the user trying to drag a tab. That requires turning on the UserMouse control style, it is off by default for controls (like TabControl) that are built-in Windows controls and use their own mouse handling.
Use Build > Build and drag the new control from the top of the toolbox onto a form. Everything still looks and acts like a regular TabControl, but do note that clicking tabs no longer changes the active tab. A side-effect of turning the UserMouse style on. Let's fix that first, paste:
protected override void OnMouseDown(MouseEventArgs e) {
for (int ix = 0; ix < this.TabCount; ++ix) {
if (this.GetTabRect(ix).Contains(e.Location)) {
this.SelectedIndex = ix;
break;
}
}
downPos = e.Location;
base.OnMouseDown(e);
}
We are storing the click location, that's needed later to detect the user dragging the tab. That requires the MouseMove event, we need to start dragging when the user moved the mouse far enough away from the original click position:
protected override void OnMouseMove(MouseEventArgs e) {
if (e.Button == MouseButtons.Left && this.TabCount > 1) {
var delta = SystemInformation.DoubleClickSize;
if (Math.Abs(e.X - downPos.X) >= delta.Width ||
Math.Abs(e.Y - downPos.Y) >= delta.Height) {
startDragging();
}
}
base.OnMouseMove(e);
}
The startDragging method needs to create a toplevel window that can be moved around with the mouse, containing a facsimile of the tab we're dragging around. We'll display it as an owned window, so it is always on top, that has the exact same size as the tab control:
private void startDragging() {
draggingBounds = this.RectangleToScreen(new Rectangle(Point.Empty, this.Size));
draggingHost = createDraggingHost(draggingBounds);
draggingPos = Cursor.Position;
draggingHost.Show(this.FindForm());
}
The createDraggingHost needs to do the heavy lifting and create a window that looks just like the tab. A borderless form we'll move around with the mouse. We'll use the TransparencyKey property to make it look similar to the dragged TabPage with a tab sticking out at the top. And make it look the same by simply letting it display a screenshot of the tabpage:
private Form createDraggingHost(Rectangle bounds) {
var host = new Form() { FormBorderStyle = FormBorderStyle.None, ControlBox = false, AutoScaleMode = AutoScaleMode.None, Bounds = this.draggingBounds, StartPosition = FormStartPosition.Manual };
host.BackColor = host.TransparencyKey = Color.Fuchsia;
var tabRect = this.GetTabRect(this.SelectedIndex);
var tabImage = new Bitmap(bounds.Width, bounds.Height);
using (var gr = Graphics.FromImage(tabImage)) {
gr.CopyFromScreen(bounds.Location, Point.Empty, bounds.Size);
gr.FillRectangle(Brushes.Fuchsia, new Rectangle(0, 0, tabRect.Left, tabRect.Height));
gr.FillRectangle(Brushes.Fuchsia, new Rectangle(tabRect.Right, 0, bounds.Width - tabRect.Right, tabRect.Height));
}
host.Capture = true;
host.MouseCaptureChanged += host_MouseCaptureChanged;
host.MouseUp += host_MouseCaptureChanged;
host.MouseMove += host_MouseMove;
host.Paint += (s, pe) => pe.Graphics.DrawImage(tabImage, 0, 0);
host.Disposed += delegate { tabImage.Dispose(); };
return host;
}
Note the use of the Capture property, that's how we detect that the user released the mouse button or interrupted the operation by any other means. We'll use the MouseMove event to move the window around:
private void host_MouseMove(object sender, MouseEventArgs e) {
draggingHost.Location = new Point(draggingBounds.Left + Cursor.Position.X - draggingPos.X,
draggingBounds.Top + Cursor.Position.Y - draggingPos.Y);
}
And finally we need to handle the completion of the drag. We'll swap tabs, inserting the dragged tab at the mouse position and destroy the window:
private void host_MouseCaptureChanged(object sender, EventArgs e) {
if (draggingHost.Capture) return;
var pos = this.PointToClient(Cursor.Position);
for (int ix = 0; ix < this.TabCount; ++ix) {
if (this.GetTabRect(ix).Contains(pos)) {
if (ix != this.SelectedIndex) {
var page = this.SelectedTab;
this.TabPages.RemoveAt(this.SelectedIndex);
this.TabPages.Insert(ix, page);
this.SelectedIndex = ix;
}
break;
}
}
draggingHost.Dispose();
draggingHost = null;
}
Looks pretty good.
since you hasn't shared ManagedTabPage code, i used default TabPage control
changes are made in method OnDragOver
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
namespace Demo
{
public class MyTabControl : TabControl
{
public MyTabControl()
{
SizeMode = TabSizeMode.Fixed;
ItemSize = new Size(224, 20);
}
#region Overriden base methods
protected override void OnDragOver(DragEventArgs e)
{
if (DesignMode)
return;
if (PointedTabPage == null) return;
e.Effect = DragDropEffects.Move;
var dragTab = e.Data.GetData(typeof(TabPage)) as TabPage;
if (dragTab == null) return;
int dropIndex = TabPages.IndexOf(PointedTabPage);
int dragIndex = TabPages.IndexOf(dragTab);
if (dragIndex == dropIndex) return;
// change position of tab
TabPages.Remove(dragTab);
TabPages.Insert(dropIndex, dragTab);
SelectedTab = dragTab;
base.OnDragOver(e);
}
protected override void OnMouseDown(MouseEventArgs e)
{
if (DesignMode)
return;
switch (e.Button)
{
case MouseButtons.Left:
DoDragDrop(PointedTabPage, DragDropEffects.Move);
break;
case MouseButtons.Middle:
TabPages.Remove(PointedTabPage);
break;
}
}
#endregion
TabPage PointedTabPage
{
get
{
return TabPages.OfType<TabPage>()
.Where((p, tabPageIndex) => GetTabRect(tabPageIndex).Contains(PointToClient(Cursor.Position)))
.FirstOrDefault();
}
}
}
}

Flickering Tab Control with MouseMove Determining What To Draw

I have been researching this all day, (Go ahead and laugh lol) and I don't see any solutions to the age old Forms problem of flickering controls. My control is a TabControl and I am using DrawMode OwnerDrawFixed. I am hooking the following events. In short I am creating a TabControl with closable "X" buttons that are 12x12 png resources. The close buttons are all gray but if I mouse over one it should use a different image (a red X).
MouseDown: Loops all TabPages and checks if I have clicked on a rectangle where I am drawing my close button image.
MouseLeave: I need to Invalidate when I leave the TabControl to ensure everything is drawn correctly
MouseMove: Loops all TabPages and checks if I have moused over a rectangle where I am drawing my close button image. If I am mousing over then I save the tab page index so my paint can change the image used for the close button.
DrawItem: Here I simply draw the image
Things I have tested but no luck...
Making my own TabControl class which inherits TabControl and in the constructor I SetStyles for OptimizedDoubleBuffering To true (I set the other suggested flags to true)
I tried overriding CreateParams so I could or this value... createParams.ExStyle |= 0x00000020; (I have no idea what this does but read a user suggested to do this.
Setting the form DoubleBuffered (does nothing)
Anyways, I can't think what to do and I have read about this for awhile.
Here is my code for all events. I just want to have close buttons on my tabs that get highlighted when I mouse over them. Thanks.
private int mousedOver = -1;//indicates which close button is moused over
private void tabControl_DrawItem(object sender, DrawItemEventArgs e)
{
e.Graphics.DrawImage(e.Index == mousedOver ? Resources.redX : Resources.grayX, e.Bounds.Right - 15, e.Bounds.Top + 4);
}
private void tabControl_MouseDown(object sender, MouseEventArgs e)
{
TabControl tc = sender as TabControl;
if (tc.TabCount == 1) return;
for (int i = 0; i < tc.TabPages.Count; i++)
{
Rectangle r = tc.GetTabRect(i);
Rectangle closeButton = new Rectangle(r.Right - 15, r.Top + 4, 12, 12);
if (closeButton.Contains(e.Location))
{
TabPage tp = tc.TabPages[i];
tc.TabPages.Remove(tp);
tp.Dispose();
break;
}
}
}
private void tabControl_MouseMove(object sender, MouseEventArgs e)
{
TabControl tc = sender as TabControl;
for (int i = 0; i < tc.TabPages.Count; i++)
{
Rectangle r = tc.GetTabRect(i);
Rectangle closeButton = new Rectangle(r.Right - 15, r.Top + 4, 12, 12);
if (closeButton.Contains(e.Location))
{
mousedOver = i;
tc.Invalidate();
return;
}
}
mousedOver = -1;
tc.Invalidate();
}
private void tabControl_MouseLeave(object sender, EventArgs e)
{
TabControl tc = sender as TabControl;
mousedOver = -1;
tc.Invalidate();
}
It does look like you are invalidating too often. Try filtering it so that you only invalidate it when the control needs to be re-painted:
private void tabControl_MouseMove(object sender, MouseEventArgs e) {
TabControl tc = sender as TabControl;
for (int i = 0; i < tc.TabPages.Count; i++) {
Rectangle r = tc.GetTabRect(i);
Rectangle closeButton = new Rectangle(r.Right - 15, r.Top + 4, 12, 12);
if (closeButton.Contains(e.Location)) {
if (mousedOver != i) {
mousedOver = i;
tc.Invalidate(r);
}
} else if (mousedOver == i) {
int oldMouse = mousedOver;
mousedOver = -1;
tc.Invalidate(tc.GetTabRect(oldMouse));
}
}
}
I would keep the CreateParams override, but as a native windows control, you can probably never totally eliminate some flicker.
You could also try setting the DoubleBuffered property of the control, by doing
Control.DoubleBuffered = true;
I know that this works with DataGridViews, ListViews, Forms and Panels.
Documentation can be found on MSDN.

removing the empty gray space in datagrid in c#

alt text http://www.freeimagehosting.net/uploads/260c1f6706.jpg
how do i remove the empty space i.e. i want the datagrid to automatically resize itself depending upon the no. of rows. i know for columns we can do that by using fill value in AutoSizeColumnMode, but there is no fill value for AutoSizeRowsMode.
It can be done, you'd have to adjust the ClientSize when a row is added or removed. However, it doesn't hide the background completely once the vertical scrollbar appears and the grid height is not a divisble by the row height. Add a new class to your project and paste the code shown below. Compile. Drop the new control from the top of the toolbox onto your form.
using System;
using System.Drawing;
using System.Windows.Forms;
class AutoSizeGrid : DataGridView {
private int gridHeight;
private bool resizing;
protected override void OnClientSizeChanged(EventArgs e) {
if (!resizing) gridHeight = this.ClientSize.Height;
base.OnClientSizeChanged(e);
}
protected override void OnRowsAdded(DataGridViewRowsAddedEventArgs e) {
setGridHeight();
base.OnRowsAdded(e);
}
protected override void OnRowsRemoved(DataGridViewRowsRemovedEventArgs e) {
setGridHeight();
base.OnRowsRemoved(e);
}
protected override void OnHandleCreated(EventArgs e) {
this.BeginInvoke(new MethodInvoker(setGridHeight));
base.OnHandleCreated(e);
}
private void setGridHeight() {
if (this.DesignMode || this.RowCount > 99) return;
int height = this.ColumnHeadersHeight + 2;
if (this.HorizontalScrollBar.Visible) height += SystemInformation.HorizontalScrollBarHeight;
for (int row = 0; row < this.RowCount; ++row) {
height = Math.Min(gridHeight, height + this.Rows[row].Height);
if (height >= gridHeight) break;
}
resizing = true;
this.ClientSize = new Size(this.ClientSize.Width, height);
resizing = false;
if (height < gridHeight && this.RowCount > 0) this.FirstDisplayedScrollingRowIndex = 0;
}
}
A bit of a hack but you may try this:
dataGridView1.BackgroundColor = System.Drawing.SystemColors.Control;
Btw this has been reported as a bug.
Set the MaxHeight property of the datagrid. e.g MaxHeight="150"
In my case I have removed the space what you have shown in the above grid with red boarder.

Categories