AutoScroll problem when using Left Dock - C# Telerik Winforms - c#

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

Related

How can I make a transparent tabPage?

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

Size adjustments for Panel control in windows forms

I have a Panel control on my winform which will display multiple panels inside that. For each inner panel I am setting its height. But some has less content to display some has more.
Panel hrvPanel = new Panel();
ArrayList hrvColl = pnlColl ; //Panel collection list gets from a Method
if(hrvColl.Count == 0)
return;
int splits = 0;
for(int p= hrvColl.Count-1;p>=0;p--)
{
Panel hrv = hrvColl[p] as Panel;
hrv.Height = 150;
hrvPanel.Controls.Add(hrv);
//Adding splliter
if(splits < hrvColl.Count - 1)
{
Splitter splitGrid = new Splitter();
splitGrid.Dock = DockStyle.Top;
hrvPanel.Controls.Add(splitGrid);
splits++;
}
}
hrvPanel.Dock = DockStyle.Top;
How to adjust the height of each inner panel based on its content size? I tried setting hrv.AutoSize to true,then I can see only the last panel And hrv.Dock = Top but the result is same.
If the outer Panel has Autosize = true you will be able to see all inner Panels. Promise.
If you don't, you have got some settings wrong. Make sure no unwanted settings of Dock and Anchor are used in the inner Panels.
It is also very simple to write code to find out the maximum of Top + Height over all inner Panels:
int max = 0;
foreach (Control ctl in panelOuter.Controls)
if (ctl.Top + ctl.Height > max) max = ctl.Top + ctl.Height;
panelOuter.Height = max + 3; // add the default margin!
This may be useful if you only want to set the Height and leave the Width as it is..other than that: The AutoSize property will do its job!
This is where WPF overcomes Winform, you probably can't do this automatically in Winforms. But you may have a work around like this-
Create an extended panel class that should know its preferred height
class ExPanel : Panel
{
public int PreferredHeight
{
get;
private set;
}
public ExPanel(int preferredHeight)
: base()
{
PreferredHeight = preferredHeight;
}
}
and then you can use this class as-
ExPanel hrvPanel = new ExPanel(150);
System.Collections.ArrayList hrvColl = pnlColl; //Panel collection list gets from a Method
if (hrvColl.Count == 0)
return;
int splits = 0;
for (int p = hrvColl.Count - 1; p >= 0; p--)
{
ExPanel hrv = hrvColl[p] as ExPanel;
hrv.Height = hrv.PreferredHeight;
hrvPanel.Controls.Add(hrv);
//Adding splliter
if (splits < hrvColl.Count - 1)
{
Splitter splitGrid = new Splitter();
splitGrid.Dock = DockStyle.Top;
hrvPanel.Controls.Add(splitGrid);
splits++;
}
}
hrvPanel.Dock = DockStyle.Top;
it's just an workaround to achieve your target, if you don't want to manage the height for your every panel.

How can a scrollable area retrieve the size of what is being displayed?

In my application I've got the following situation:
I've got a Windows Form with a Tab Control with several tabs. Each tab contains arbitrary content which is added by other classes upon startup or during runtime.
I want to set up the tabs in a way that scrollbars appear automatically as soon as the Form is too small for the tab's panel to display everything.
What I've tried so far is setting the tab page's AutoScroll = true and setting the AutoScrollMinSize property to the size of the panel.
This did not work as expected as the panel's Size always seems to be (200, 100) independent of its contents.
I've created a small example application (code below) which demonstrates the issue. If you resize the form, you'll see that scroll bars only appear if the Form gets smaller than the panel (default size of (200, 100)) rather than the text box in the panel (size of 300, 150). If you set AutoScrollMinSize manually (uncomment line 34), it behaves as expected.
The question is: How can the tab page retrieve the actual size of what is displayed in it?
I could probably recurse through all controls and try calculating the size myself - but this feels really bad.
PS: Please do not suggest setting the size of the panel to the size of the label, as the actual panels are much more complex than that. ;-)
Code:
Simply create an Application in Visual Studio and override Program.cs with the following code:
using System;
using System.Windows.Forms;
namespace ScrollbarTest
{
static class Program
{
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
var sampleForm = CreateSampleForm();
Application.Run(sampleForm);
}
private static Form CreateSampleForm()
{
var sampleForm = new Form() { };
var tabControl = new TabControl() { Dock = DockStyle.Fill };
var tabPage = new TabPage("Test") { AutoScroll = true };
sampleForm.Controls.Add(tabControl);
tabControl.TabPages.Add(tabPage);
var samplePanel = CreateSamplePanel();
tabPage.Controls.Add(samplePanel);
// this does not provide the right size
tabPage.AutoScrollMinSize = samplePanel.Size;
// uncomment this to make it work
//tabPage.AutoScrollMinSize = new System.Drawing.Size(300, 150);
return sampleForm;
}
private static Control CreateSamplePanel()
{
// As an example, create a panel with a text box with a fixed size.
var samplePanel = new Panel() { Dock = DockStyle.Fill };
var sampleSize = new System.Drawing.Size(300, 150);
var textBox = new TextBox()
{
Dock = DockStyle.Fill,
MinimumSize = sampleSize,
MaximumSize = sampleSize,
Size = sampleSize
};
samplePanel.Controls.Add(textBox);
return samplePanel;
}
}
}
The samplePanel.Size returns (200,100). In your CreateSamplePanel method, if you set samplePanel.MinimumSize = sampleSize; then your code will work.
Panels don't calculate their size properties (e.g. Size, MinimumSize, PreferredSize) based on their child controls. You will have to subclass Panel and provide that behavior. Even TableLayoutPanel and FlowLayoutPanel don't correctly calculate the PreferredSize property, which is surprising. At the very least, normally you override the GetPreferredSize(Size proposedSize) method, and optionally have the MinimumSize property return the PreferredSize property.
It's worth noting that DockStyle.Fill and MinimumSize are at odds with each other. TabPage controls are inherently DockStyle.Fill mode, which is why you have to set the AutoScrollMinSize property.
Edit: Isn't there any existing function which retrieves the total required size of a list of controls (recursively), e.g. through their X/Y and Size?
It's up to the host container itself (e.g. TableLayoutPanel) to calculate its PreferredSize correctly because only it knows the exact details of how its layout is performed.
You can set the AutoSize property to true and then hope that GetPreferredSize(...)/PreferredSize calculates the right size. For TableLayoutPanel, I recall there was a case where it wasn't calculating correctly and I had to subclass it and override the GetPreferredSize(...) method. GetPreferredSize(...) won't be called unless AutoSize is true.
If you're talking about a plain Panel or UserControl, by default these use the WYSIWYG LayoutEngine, and do not calculate the PreferredSize. You could subclass and then calculate maximum control.X + control.Width and same thing for height, and use that as the preferred size.
First try setting AutoSize to true and see if that works for you. If not, you might have to override the GetPreferredSize(...) method. Here is a crude example:
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
var sampleForm = new Form() { AutoScroll = true };
var panel = new MyPanel() { AutoSize = true, AutoSizeMode = AutoSizeMode.GrowAndShrink, BackColor = Color.LightYellow };
for (int i = 0; i < 6; i++) {
for (int j = 0; j < 3; j++) {
Button b = new Button { Text = "Button" + panel.Controls.Count, AutoSize = true };
b.Click += delegate {
MessageBox.Show("Preferred Size: " + panel.PreferredSize);
};
panel.Controls.Add(b, j, i);
}
}
sampleForm.Controls.Add(panel);
Application.Run(sampleForm);
}
private class MyPanel : TableLayoutPanel {
public override Size MinimumSize {
get {
return PreferredSize;
}
set {
}
}
public override Size GetPreferredSize(Size proposedSize) {
Size s = new Size();
int[] harr = new int[100];//this.RowCount];
int[] warr = new int[100];//this.ColumnCount];
foreach (Control c in this.Controls) {
var cell = this.GetPositionFromControl(c);
var ps = c.PreferredSize;
Padding m = c.Margin;
int w = ps.Width + m.Horizontal;
int h = ps.Height + m.Vertical;
if (w > warr[cell.Column])
warr[cell.Column] = w;
if (h > harr[cell.Row])
harr[cell.Row] = h;
}
foreach (int w in warr)
s.Width += w;
foreach (int h in harr)
s.Height += h;
return s;
}
}

Manage windows inside a panel with a 'Windows'-like menu

I've a panel.
I add WinForms inside it. The WinForms added have the TopLevel and Visible properties set to FALSE and TRUE.
I can do a panel.SetChildIndex(WinForm1,0) to bring WinForm1 to front.
What I've not managed to do is keep a track of the actual ChildIndex of the panel.
The idea is to have buttons that opens forms inside the panel, and that when the panel opens a new button is added in a Windows menu.
Something like when many files are open on a VS Project, you can go to Window menu and select one. Also, if you change the active page by clicking the page, the Window menu auto-updates and checks the actual active page.
I want to do this, but with a panel container. I've managed to get done everithing, but not the the Window menu auto-updates and checks the actual active page part.
Isn't there an event fired when BringToFront() or SetChildIndex(form, index) are called? Any event when I click another form that's inside the panel and it becomes the "active one"? Or some property of the panel that I can keep track of that changes when active form changes?
It is taken from here
When Control's ZOrder is chaged layout operation is always performed
in control's container control.
When I subscribed to container's Layout event and called
BringToFront() it showed me Control that changed its
ZOrder(LayoutEventArgs.AffectedControl) and changed property
(LayoutEventArgs.AffectedProperty).
Found that when a form inside a panel is closed, the Controls property of the panel gets reindexed, where the index zero is the form that gets the new focus. Now that I've a way to check the form that's in front when I close another one, windows administration in panels is done.
Going to put the source code, maybe it can help someone :)
Please note that I'm using a RadRibbonForm, a standard panel, and RadForms inside the panel. Rad's are from Telerik. Some things should change to make this work on standardWinForms, but the changes are minimal.
Also, I'm not using a menu that shows the forms, I'm using RadButtonElement's in a page of the ribbon menu instead.
AddRadFormWindow must be called to put a window and manage it automatically.
Example of adding a window:
AddRadFormWindow(typeof (MyRadForm))
Now, the source. It must be inside the code of the RadRibbonForm's class.
public static class ExtensionsRadForm
{
[DllImport("user32.dll")]
private static extern int ShowWindow(IntPtr hWnd, uint msg);
public static void Deminimize(this RadForm form)
{
if (form.WindowState == FormWindowState.Minimized)
ShowWindow(form.Handle, 9);
}
}
private void RefreshButtonsChecks(string windowName)
{
if (windowName != null)
{
principalPanel.Controls[windowName].BringToFront();
}
if (principalPanel.Controls.Count > 0)
{
if (principalPanel.Controls.Cast<RadForm>().Any(radForm => radForm.WindowState != FormWindowState.Minimized))
{
foreach (RadItem item in radRibbonBarGroupOpenWindows.Items)
{
var buttonBorder = ((RadButtonElement) item).BorderElement;
if (item.Name == panelPrincipal.Controls[0].Name + "Button")
{
buttonBorder.ForeColor = Color.LimeGreen;
buttonBorder.BottomColor = Color.LimeGreen;
buttonBorder.TopColor = Color.LimeGreen;
buttonBorder.LeftColor = Color.LimeGreen;
buttonBorder.RightColor = Color.LimeGreen;
principalPanel.Controls[0].Focus();
}
else
{
buttonBorder.ForeColor = Color.Transparent;
buttonBorder.BottomColor = Color.Transparent;
buttonBorder.TopColor = Color.Transparent;
buttonBorder.LeftColor = Color.Transparent;
buttonBorder.RightColor = Color.Transparent;
}
}
}
else
{
foreach (RadItem item in radRibbonBarGroupAbiertas.Items)
{
var buttonBorder = ((RadButtonElement)item).BorderElement;
buttonBorder.ForeColor = Color.Transparent;
buttonBorder.BottomColor = Color.Transparent;
buttonBorder.TopColor = Color.Transparent;
buttonBorder.LeftColor = Color.Transparent;
buttonBorder.RightColor = Color.Transparent;
}
}
}
}
private void PrincipalPanelLayout(object sender, LayoutEventArgs e)
{
RefreshButtonsChecks(null);
}
private void RadButtonElementCloseAllWindowsClick(object sender, EventArgs e)
{
int limitButtons = radRibbonBarGroupOpenWindows.Items.Count;
for (int index = 0; index < limitButtons; index++)
{
RadItem radItem = radRibbonBarGroupOpenWindows.Items[0];
radItem.Dispose();
}
int limitControls = principalPanel.Controls.Count;
for (int index = 0; index < limitControls; index++)
{
Control control = principalPanel.Controls[0];
control.Dispose();
}
Update();
GC.Collect();
}
private void AddRadFormWindow(Type windowToAdd)
{
if (!principalPanel.Controls.ContainsKey(windowToAdd.Name))
{
var window = (RadForm) Activator.CreateInstance(windowToAdd);
window.TopLevel = false;
window.Visible = true;
window.FormClosing += (method, args) =>
{
radRibbonBarGroupOpenWindows.Items[window.Name + "Button"].Dispose();
GC.Collect();
};
window.Enter += (method, args) => RefreshButtonsChecks(window.Name);
var closeMenuItem = new RadMenuItem("Close");
closeMenuItem.MouseDown += (method, args) =>
{
panelPrincipal.Controls[window.Name].Dispose();
radRibbonBarGroupOpenWindows.Items[window.Name + "Button"].Dispose();
};
var contextMenu = new RadContextMenu();
contextMenu.Items.Add(closeMenuItem);
var button = new RadButtonElement(window.Text) {Name = window.Name + "Button"};
button.MouseDown += (method, args) =>
{
switch (args.Button)
{
case MouseButtons.Left:
if (((RadForm) principalPanel.Controls[window.Name]).WindowState ==
FormWindowState.Minimized)
((RadForm) principalPanel.Controls[window.Name]).Deminimize();
principalPanel.Controls[window.Name].BringToFront();
principalPanel.Controls[window.Name].Focus();
break;
case MouseButtons.Right:
contextMenu.Show(MousePosition);
break;
}
};
radRibbonBarGroupOpenWindows.Items.Add(button);
principalPanel.Controls.Add(window);
principalPanel.Controls[window.Name].BringToFront();
principalPanel.Controls[window.Name].Focus();
}
principalPanel.Controls[windowToAdd.Name].BringToFront();
principalPanel.Controls[windowToAdd.Name].Focus();
Update();
GC.Collect();
}
public Constructor()
{
panelPrincipal.Layout += PanelPrincipalLayout;
}

C#: Changing Button BackColor has no effect

I'm having a problem with C# buttons in Windows Forms.
I've create a number of buttons programmatically and add them to a form afterwards.
Interestingly, every modification to those buttons (location and size) except for the modification of the BackColor is readily executed. Only the button's color remains unchanged.
The code looks something like this:
public class SimpleSortAlgDisplayer : ISortAlgDisplayer
{
#region ISortAlgDisplayer Member
void ISortAlgDisplayer.Init(int[] Data)
{
this.DataLength = Data.Length;
this.DispWin = new CurrentSortStateWin();
this.DispWin.Show();
this.DispWin.Size = new Size(60 + (10 * this.DataLength), 120);
this.myArrayElements = new Button[this.DataLength];
for (int i = 0; i < this.DataLength; i++)
{
this.myArrayElements[i] = new Button();
//begin of series of invoked actions
this.myArrayElements[i].Size=new Size(5,(int)(((80)*(double)Data[i])/1000));
this.myArrayElements[i].Location = new Point(30 + (i * 10), 90-(this.myArrayElements[i].Size.Height));
this.myArrayElements[i].Enabled = true;
this.myArrayElements[i].BackColor = Color.MidnightBlue;
this.myArrayElements[i].UseVisualStyleBackColor = true;
this.DispWin.Controls.Add(this.myArrayElements[i]);
this.myArrayElements[i].Refresh();
}
}
Ideas anyone?
A similar question was asked here but the answers to it were not very helpful:
Trying to use Invoke gives me the run-time error that DispWin is not yet created.
Setting UseVisualStyleBackColor to false changes nothing.
Setting BackColor and ForeColor or Showing DispWin only after adding and formatting the Buttons also had no effect.
Where am I going wrong?
You are trying to set up the color, but then you override it saying UseVisualStyleBackColor = true
if you want to use your custom color, you need to set UseVisualStyleBackColor to false or the color will only be applied to the button upon mouse over.
a simple test uploaded to GitHub
public partial class mainForm : Form
{
Random randonGen = new Random();
public mainForm()
{
InitializeComponent();
}
private void mainForm_Load(object sender, EventArgs e)
{
populate();
}
private void populate()
{
Control[] buttonsLeft = createButtons().ToArray();
Control[] buttonsRight = createButtons().ToArray();
pRight.Controls.AddRange(buttonsRight);
pLeft.Controls.AddRange(buttonsLeft);
}
private List<Button> createButtons()
{
List<Button> buttons = new List<Button>();
for (int i = 1; i <= 5; i++)
{
buttons.Add(
new Button()
{
Size = new Size(200, 35),
Enabled = true,
BackColor = GetColor(),
ForeColor = GetColor(),
UseVisualStyleBackColor = false,
Left = 20,
Top = (i * 40),
Text = String.Concat("Button ", i)
});
}
return buttons;
}
private Color GetColor()
{
return Color.FromArgb(randonGen.Next(255), randonGen.Next(255), randonGen.Next(255));
}
}
result
If FlatStyle for button is set to System, it will not show any backcolor rather use backcolor from template of system colors.
Make sure you do not have a BackgroundImage set. This overrides the BackColor.
In the properties window for Button. Look for 'FlatStyle' property and change it from 'System' to 'Flat', 'Standard' or 'Popup' and you will be able to see the button color change. I just fixed my issue with this.

Categories