How to size all panels as fill in form1 window without changing panels size? I searched on Google. very difficult to find. That why i want to help. like in below Thanks.
If 3 panels this will be resized:
4 Panels:
5 Panels:
9 Panels:
You can use a FlowLayoutPanel. Insert in your form and set Dock=Fill in the designer. Add this const to your form:
private const int PanelSize = 200;
In the constructor:
this.flowLayoutPanel1.Resize += this.OnFlowLayoutPanel1_Resize;
this.OnFlowLayoutPanel1_Resize(this.flowLayoutPanel1, EventArgs.Empty);
And use this method to create/destroy the panels:
private void OnFlowLayoutPanel1_Resize(object sender, EventArgs e)
{
// At least, one panel
var columns = Math.Max(1, this.flowLayoutPanel1.Width / (double)PanelSize);
var rows = Math.Max(1, this.flowLayoutPanel1.Height / (double)PanelSize);
var panelsCount = this.flowLayoutPanel1.Controls.Count;
var requiredPanelsCount = rows * columns;
var diff = requiredPanelsCount - panelsCount;
if (diff > 0)
{
// We need more panels: create it
for (int i = 0; i < diff; i++)
{
var panel = new Panel
{
Size = new Size(PanelSize, PanelSize),
TabIndex = this.flowLayoutPanel1.Controls.Count,
BackColor = GetBackColor()
};
this.flowLayoutPanel1.Controls.Add(panel);
}
}
else
{
// Remove unneeded panels
for (int i = 0; i < diff; i++)
{
this.flowLayoutPanel1.Controls.RemoveAt(
this.flowLayoutPanel1.Controls.Count - 1);
}
}
}
I have used this method to set a color:
private Color GetBackColor()
{
var colors = new[]
{
Color.Black, Color.Red, Color.Green, Color.Blue, Color.White
};
var index = this.flowLayoutPanel1.Controls.Count % colors.Length;
return colors[index];
}
Adapt it to your needs.
If you need fill entire form, you must work with a variable PanelSize. Use a minimum and maximum size for the panels instead a fixed value.
I'm creating/removing Panels to fill entire space. If you only need fixed panels in the form, you don't need the resize event. The FlowLayoutControl do what you need.
Related
I am adding 8 panels to a "flowLayoutPanel1". It works fine.
The problem is that it comes 4 panels on the first"row" and then 4 panels on next "row".
The thing is that I have made the size of the "flowLayoutPanel1" to visually show 3 panels on each "row", - so in this case, half of the 4th panel on each row are not seen.
But if I add them in the designer manually, it do come 3 panels on each "row" which I want.
I wonder why this is happening when I add them dynamically with this code?
flowLayoutPanel1.Controls.Clear(); int count = 0;
for (int n = 0; n < 4; n++)
{
for (int i = 0; i < latestImageLIST.Count; i++)
{
//Now add all images as panels
String imagefile = latestImageLIST[i];
if (File.Exists(imagefile))
{
Panel panel = new Panel(); count++;
panel.Name = "thepanel" + count;
panel.Size = new Size(284, 160);
panel.Margin = new Padding(3);
Image image = Image.FromFile(imagefile);
panel.BackgroundImage = image;
panel.BackgroundImageLayout = ImageLayout.Stretch;
panel.Tag = "thepanel" + count;
panel.Click += new System.EventHandler(this.panel216_Click);
flowLayoutPanel1.Controls.Add(panel);
}
}
}
I recommend using TableLayoutPanel, which is an alternative to FlowLayoutPanel. You can first determine the row and column based on the number of images you need to load, then dynamically create a Panel through a loop and add it to the specified row and column.
public void AddImages(int row, int col)
{
TableLayoutPanel tlp = new TableLayoutPanel();
int prow = 100 / row, pcol = 100 / col;
for(var i=0;i<row;i++)
{
tlp.RowStyles.Add(new RowStyle(SizeType.Percent, prow));
}
for(var i=0;i<col;i++)
{
tlp.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, pcol));
}
//modify the add logic according to your requirement.
tlp.Controls.Add(new Panel() { Dock = DockStyle.Fill }, 1, 1);
//todo...
this.Controls.Add(tlp);
}
I'm trying to create an autosizing button grid using a TableLayoutPanel. When I add columns at runtime with the following code they are not being sized evenly:
tableLayoutPanel.ColumnCount += 1;
for (var i = 0; i < tableLayoutPanel.RowCount; i++) {
var button = new Button {
Margin = Padding.Empty,
Padding = Padding.Empty,
Dock = DockStyle.Fill
}
tableLayoutPanel.Controls.Add(button);
}
The initial form with 1 column:
Adding a 2nd column:
Adding a 3rd column:
Is there a way to make the columns autosize evenly without manually calculating the dimensions?
It's necessary to explicitly reset the column styles:
private void RecalculateColumnStyles()
{
var cols = tableLayoutPanel.ColumnCount;
var pct = (float) 100 / cols;
tableLayoutPanel.SuspendLayout();
tableLayoutPanel.ColumnStyles.Clear();
for (var i = 0; i < cols; i++) {
tableLayoutPanel.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, pct));
}
tableLayoutPanel.ResumeLayout();
}
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.
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;
}
}
I have an issue with TableLayoutPanel, which fills an userControl (DockStyle.Fill). I face a trouble, when this control is being resized, I need all cells to change their size, but only last row and last column changes size (so whole tableLayoutPanel fills the control). I change this controler size using Bounds property.
let's say I wrote following code:
// creating tableLayoutPanel:
private void createTableLayoutPanel(int count)
{
tableLayoutPanel = new TableLayoutPanel();
tableLayoutPanel.MouseClick += new MouseEventHandler(this.observe_MouseClick);
tableLayoutPanel.AutoSize = true;
tableLayoutPanel.ColumnCount = 3;
tableLayoutPanel.RowCount = count;
tableLayoutPanel.Dock = DockStyle.Fill;
tableLayoutPanel.AutoSize = true;
this.Controls.Add(tableLayoutPanel);
}
// resizing:
private void OnMouseWheel(MouseEventArgs e)
{
this.Bounds = new Rectangle(this.Location.X, this.Location.Y, (int)(this.Width*newScale),(int)(this.Height*newScale));
}
Thanks for any help.
For each row, add an item to the TableLayoutPanel's RowStyles collection with SizeType = SizeType.Percent and Height = 100 / tableLayoutPanel.RowCount. Do the same with the ColumnStyles collection.