Remove Row inside TableLayoutPanel makes a layout problem - c#

I have a WinForms application that has a TableLayoutPanel; this is the definition code:
tableLayoutPanel1 = new TableLayoutPanel();
tableLayoutPanel1.Dock = DockStyle.Fill;
tableLayoutPanel1.AutoScroll = true;
tableLayoutPanel1.RowCount = users.Count + 1;
tableLayoutPanel1.ColumnCount = 1;
tableLayoutPanel1.GrowStyle = TableLayoutPanelGrowStyle.FixedSize;
tableLayoutPanel1.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 100F));
foreach (String user in users)
{
tableLayoutPanel1.RowStyles.Add(new RowStyle(SizeType.Absolute, 600F));
}
tableLayoutPanel1.RowStyles.Add(new RowStyle(SizeType.Absolute, 600F));
int index = 0;
foreach (String user in users)
{
AddDockedControl(index, user);
index++;
}
AddDockedControl(index, null);
panel1.Controls.Add(tableLayoutPanel1);
private void AddDockedControl(int row, String userName)
{
AccountRowUC newUser = new AccountRowUC(this, userName, row);
newUser.BorderStyle = BorderStyle.FixedSingle;
newUser.Dock = DockStyle.Top;
tableLayoutPanel1.Controls.Add(newUser, 0, row);
}
Now, when I want to remove one of the rows, I'm using this code:
public void RemoveRowAtIndex(int index)
{
if (index >= tableLayoutPanel1.RowCount)
return;
// delete all controls of row that we want to delete
for (int i = 0; i < tableLayoutPanel1.ColumnCount; i++)
{
var control = tableLayoutPanel1.GetControlFromPosition(i, index);
tableLayoutPanel1.Controls.Remove(control);
}
// move up row controls that comes after row we want to remove
for (int i = index + 1; i < tableLayoutPanel1.RowCount; i++)
{
for (int j = 0; j < tableLayoutPanel1.ColumnCount; j++)
{
var control = tableLayoutPanel1.GetControlFromPosition(j, i);
if (control != null)
tableLayoutPanel1.SetRow(control, i - 1);
}
}
// remove last row
tableLayoutPanel1.RowStyles.RemoveAt(tableLayoutPanel1.RowCount - 1);
//tableLayoutPanel1.RowStyles.RemoveAt(index);
tableLayoutPanel1.RowCount--;
}
The problem is that when I remove a Row, a big space is left at the bottom of the table: the TableLayoutPanel won't reclaim the size of panel1.

A solution base on the layout described in the comments and this answer, previously posted:
Center multiple rows of controls in a FlowLayoutPanel
Description:
(Full code of a test Form provided at bottom of this post)
Create a new Form (here, named frmTLPTest1)
Add two Panels. One is used to host some buttons, the other one will be the Container of a TableLayoutPanel.
Set the Container panel to AutoScroll = true, AutoSizeMode = AutoSizeMode.GrowAndShrink, set all the Anchors (Left, Top, Right, Bottom)
Inside the Container panel, drop a new TableLayoutPanel: set it to AutoSize = true, AutoSizeMode = AutoSizeMode.GrowAndShrink, Dock = DockStyle.Top
Remove all Rows and Columns from the TableLayoutPanel except one of each (you cannot remove all). Set the dimensions of both to AutoSize.
Important note (also reported in the linked answer):
In the Form constructor, one of the RowStyles is removed. This is
important: the TLP will keep 2 RowStyles. One is applied to the
existing Row; the second style will be applied to the first Row you
add: to the first one only, not the others. If this style is not
removed, it will compromise the layout.
The core methods used to Add Rows to/Remove Rows from the TableLayoutPanel, make use of a FlowLayoutPanel as the TLP Row content and can also be used as Container of other controls, eventually.
TlpAddRow(TableLayoutPanel tlp, bool addRowCount) method:
Adds a new FlowLayoutPanel to the Cell of the TableLayoutPanel specified and adds a new Row if requested.
Since the Designer won't allow to remove all the Rows, the First Row (FlowLayoutPanel) must not increment the Rows count: the addRowCount argument will be set to false.
private Control TlpAddRow(TableLayoutPanel tlp, bool addRowCount)
{
var flp = new FlowLayoutPanel() {
Anchor = AnchorStyles.Top | AnchorStyles.Bottom,
AutoSize = true,
AutoSizeMode = AutoSizeMode.GrowAndShrink,
};
tlp.SuspendLayout();
if (addRowCount) tlp.RowCount += 1;
tlp.Controls.Add(flp, 0, tlp.RowCount - 1);
tlp.ResumeLayout(true);
return flp;
}
TLPRemoveRow(TableLayoutPanel tlp, Control control) method (overloaded):
Allows to remove a Row from the specified TableLayoutPanel. The Row to be removed can be derived from the Control that is used as the Row Container (a FlowLayoutPanel, here, but it could be a Panel, another TableLayoutPanel, or some other type of Container control).
The Row can also be removed by directly specifying the Row index.
private void TLPRemoveRow(TableLayoutPanel tlp, Control control)
{
int ctlRow = tlp.GetRow(control);
TLPRemoveRow(tlp, ctlRow);
}
private void TLPRemoveRow(TableLayoutPanel tlp, int row)
{
if (row < tlp.RowCount - 1) {
for (int i = row; i < tlp.RowCount - 1; i++) {
tlp.SetRow(tlp.GetControlFromPosition(0, i + 1), i);
}
}
tlp.RowCount -= 1;
}
Visual results of this Layout:
Since it's easier to understand how it work by testing rather than explaining, here's the full layout of the Form:
Test Form (frmTLPTest1):
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
public partial class frmTLPTest1 : Form
{
public frmTLPTest1()
{
InitializeComponent();
tlp1.RowStyles.RemoveAt(1);
}
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
TlpAddRow(tlp1, false);
}
Random rnd = new Random();
Size[] sizes = new Size[] { new Size(75, 75), new Size(100, 100), new Size(125, 125)};
Color[] colors = new Color[] { Color.Red, Color.LightGreen, Color.YellowGreen, Color.SteelBlue };
Control selectedObject = null;
Control selectedParent = null;
private void btnAddControl_Click(object sender, EventArgs e)
{
Size size = new Size(125, 125);
if (chkRandom.Checked) size = sizes[rnd.Next(sizes.Length)];
var pBox = new PictureBox() {
Anchor = AnchorStyles.None,
BackColor = colors[rnd.Next(colors.Length)],
MinimumSize = size,
Size = size
};
bool drawborder = false;
pBox.MouseEnter += (s, evt) => { drawborder = true; pBox.Invalidate(); };
pBox.MouseLeave += (s, evt) => { drawborder = false; pBox.Invalidate(); };
pBox.MouseDown += (s, evt) => { selectedParent = pBox.Parent;
selectedObject = pBox; pBox.Invalidate();
};
pBox.Paint += (s, evt) => {
if (drawborder) {
ControlPaint.DrawBorder(evt.Graphics, pBox.ClientRectangle,
Color.White, ButtonBorderStyle.Solid);
}
};
if (tlp1.RowCount == 0) TlpAddRow(tlp1, true);
var ctl = tlp1.GetControlFromPosition(0, tlp1.RowCount - 1);
int overallWith = 0;
if (ctl.Controls?.Count > 0) {
overallWith = ctl.Controls.OfType<Control>().Sum(c => c.Width + c.Margin.Left + c.Margin.Right);
}
overallWith += ctl.Margin.Right + ctl.Margin.Left + pBox.Size.Width + pBox.Margin.Left + pBox.Margin.Right;
if (overallWith >= tlp1.Width) {
ctl = TlpAddRow(tlp1, true);
}
ctl.Controls.Add(pBox);
}
private void btnRemoveRow_Click(object sender, EventArgs e)
{
if (selectedParent is null) return;
if (selectedParent.Controls.Count > 0) {
for (int i = 0; i == selectedParent.Controls.Count - 1; i++) {
selectedParent.Controls[i].Dispose();
}
}
TLPRemoveRow(tlp1, selectedParent);
selectedParent.Dispose();
}
private void btnRemoveControl_Click(object sender, EventArgs e)
{
if (selectedObject is null) return;
Control parent = selectedObject.Parent;
selectedObject.Dispose();
if (parent?.Controls.Count == 0) {
TLPRemoveRow(tlp1, parent);
parent.Dispose();
}
}
private Control TlpAddRow(TableLayoutPanel tlp, bool addRowCount)
{
var flp = new FlowLayoutPanel() {
Anchor = AnchorStyles.Top | AnchorStyles.Bottom,
AutoSize = true,
AutoSizeMode = AutoSizeMode.GrowAndShrink,
};
tlp.SuspendLayout();
if (addRowCount) tlp.RowCount += 1;
tlp.Controls.Add(flp, 0, tlp.RowCount - 1);
tlp.ResumeLayout(true);
return flp;
}
private void TLPRemoveRow(TableLayoutPanel tlp, Control control)
{
int ctlRow = tlp.GetRow(control);
TLPRemoveRow(tlp, ctlRow);
}
private void TLPRemoveRow(TableLayoutPanel tlp, int row)
{
if (row < tlp.RowCount - 1) {
for (int i = row; i < tlp.RowCount - 1; i++) {
tlp.SetRow(tlp.GetControlFromPosition(0, i + 1), i);
}
}
tlp.RowCount -= 1;
}
}
Test Form Designer:
partial class frmTLPTest1
{
private System.ComponentModel.IContainer components = null;
protected override void Dispose(bool disposing)
{
if (disposing && (components != null)) {
components.Dispose();
}
base.Dispose(disposing);
}
private void InitializeComponent()
{
this.panToolbar = new System.Windows.Forms.Panel();
this.btnRemoveRow = new System.Windows.Forms.Button();
this.chkRandom = new System.Windows.Forms.CheckBox();
this.btnRemoveControl = new System.Windows.Forms.Button();
this.btnAddControl = new System.Windows.Forms.Button();
this.panBackground = new System.Windows.Forms.Panel();
this.tlp1 = new System.Windows.Forms.TableLayoutPanel();
this.panToolbar.SuspendLayout();
this.panBackground.SuspendLayout();
this.SuspendLayout();
//
// panToolbar
//
this.panToolbar.BackColor = System.Drawing.Color.DarkOliveGreen;
this.panToolbar.Controls.Add(this.btnRemoveRow);
this.panToolbar.Controls.Add(this.chkRandom);
this.panToolbar.Controls.Add(this.btnRemoveControl);
this.panToolbar.Controls.Add(this.btnAddControl);
this.panToolbar.Dock = System.Windows.Forms.DockStyle.Bottom;
this.panToolbar.Location = new System.Drawing.Point(0, 359);
this.panToolbar.Name = "panToolbar";
this.panToolbar.Size = new System.Drawing.Size(552, 55);
this.panToolbar.TabIndex = 2;
//
// btnRemoveRow
//
this.btnRemoveRow.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(32)))), ((int)(((byte)(32)))), ((int)(((byte)(32)))));
this.btnRemoveRow.FlatAppearance.MouseDownBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(192)))), ((int)(((byte)(64)))), ((int)(((byte)(0)))));
this.btnRemoveRow.FlatAppearance.MouseOverBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(128)))), ((int)(((byte)(64)))), ((int)(((byte)(0)))));
this.btnRemoveRow.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.btnRemoveRow.ForeColor = System.Drawing.Color.White;
this.btnRemoveRow.Location = new System.Drawing.Point(261, 11);
this.btnRemoveRow.Name = "btnRemoveRow";
this.btnRemoveRow.Size = new System.Drawing.Size(119, 34);
this.btnRemoveRow.TabIndex = 4;
this.btnRemoveRow.Text = "Remove Row";
this.btnRemoveRow.UseVisualStyleBackColor = false;
this.btnRemoveRow.Click += new System.EventHandler(this.btnRemoveRow_Click);
//
// chkRandom
//
this.chkRandom.AutoSize = true;
this.chkRandom.ForeColor = System.Drawing.Color.White;
this.chkRandom.Location = new System.Drawing.Point(446, 20);
this.chkRandom.Name = "chkRandom";
this.chkRandom.Size = new System.Drawing.Size(94, 19);
this.chkRandom.TabIndex = 3;
this.chkRandom.Text = "Random Size";
this.chkRandom.UseVisualStyleBackColor = true;
//
// btnRemoveControl
//
this.btnRemoveControl.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(32)))), ((int)(((byte)(32)))), ((int)(((byte)(32)))));
this.btnRemoveControl.FlatAppearance.MouseDownBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(192)))), ((int)(((byte)(64)))), ((int)(((byte)(0)))));
this.btnRemoveControl.FlatAppearance.MouseOverBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(128)))), ((int)(((byte)(64)))), ((int)(((byte)(0)))));
this.btnRemoveControl.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.btnRemoveControl.ForeColor = System.Drawing.Color.White;
this.btnRemoveControl.Location = new System.Drawing.Point(136, 11);
this.btnRemoveControl.Name = "btnRemoveControl";
this.btnRemoveControl.Size = new System.Drawing.Size(119, 34);
this.btnRemoveControl.TabIndex = 2;
this.btnRemoveControl.Text = "Remove Control";
this.btnRemoveControl.UseVisualStyleBackColor = false;
this.btnRemoveControl.Click += new System.EventHandler(this.btnRemoveControl_Click);
//
// btnAddControl
//
this.btnAddControl.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(32)))), ((int)(((byte)(32)))), ((int)(((byte)(32)))));
this.btnAddControl.FlatAppearance.MouseDownBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(192)))), ((int)(((byte)(64)))), ((int)(((byte)(0)))));
this.btnAddControl.FlatAppearance.MouseOverBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(128)))), ((int)(((byte)(64)))), ((int)(((byte)(0)))));
this.btnAddControl.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.btnAddControl.ForeColor = System.Drawing.Color.White;
this.btnAddControl.Location = new System.Drawing.Point(11, 11);
this.btnAddControl.Name = "btnAddControl";
this.btnAddControl.Size = new System.Drawing.Size(119, 34);
this.btnAddControl.TabIndex = 0;
this.btnAddControl.Text = "Add Control";
this.btnAddControl.UseVisualStyleBackColor = false;
this.btnAddControl.Click += new System.EventHandler(this.btnAddControl_Click);
//
// panBackground
//
this.panBackground.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.panBackground.AutoScroll = true;
this.panBackground.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink;
this.panBackground.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(32)))), ((int)(((byte)(32)))), ((int)(((byte)(32)))));
this.panBackground.Controls.Add(this.tlp1);
this.panBackground.Location = new System.Drawing.Point(0, 0);
this.panBackground.Name = "panBackground";
this.panBackground.Size = new System.Drawing.Size(552, 360);
this.panBackground.TabIndex = 3;
//
// tlp1
//
this.tlp1.AutoSize = true;
this.tlp1.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink;
this.tlp1.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(32)))), ((int)(((byte)(32)))), ((int)(((byte)(32)))));
this.tlp1.CellBorderStyle = System.Windows.Forms.TableLayoutPanelCellBorderStyle.Single;
this.tlp1.ColumnCount = 1;
this.tlp1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle());
this.tlp1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 20F));
this.tlp1.Dock = System.Windows.Forms.DockStyle.Top;
this.tlp1.Location = new System.Drawing.Point(0, 0);
this.tlp1.Name = "tlp1";
this.tlp1.RowCount = 1;
this.tlp1.RowStyles.Add(new System.Windows.Forms.RowStyle());
this.tlp1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 1F));
this.tlp1.Size = new System.Drawing.Size(552, 2);
this.tlp1.TabIndex = 4;
//
// frmTLPTest1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(96F, 96F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi;
this.ClientSize = new System.Drawing.Size(552, 414);
this.Controls.Add(this.panBackground);
this.Controls.Add(this.panToolbar);
this.Font = new System.Drawing.Font("Segoe UI", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.Name = "frmTLPTest1";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "frmTLPTest1";
this.Load += new System.EventHandler(this.SOfrmTest1_Load);
this.panToolbar.ResumeLayout(false);
this.panToolbar.PerformLayout();
this.panBackground.ResumeLayout(false);
this.panBackground.PerformLayout();
this.ResumeLayout(false);
}
private System.Windows.Forms.Panel panToolbar;
private System.Windows.Forms.Button btnAddControl;
private System.Windows.Forms.Button btnRemoveControl;
private System.Windows.Forms.CheckBox chkRandom;
private System.Windows.Forms.Panel panBackground;
private System.Windows.Forms.TableLayoutPanel tlp1;
private System.Windows.Forms.Button btnRemoveRow;
}

Related

Dynamically update button

I am attempting to dynamically add a list of buttons:
private void updateClientListUI()
{
if (this.InvokeRequired)
{
this.Invoke(new MethodInvoker(this.updateClientListUI));
}
else
{
int count = 1;
int x = 0;
int y = 0;
for (int i = 0; i < 5; i++)
{
Button btn = new Button();
btn.Text = count.ToString();
btn.Name = count.ToString();
btn.Size = new Size(35, 35);
btn.Location = new Point(150, 150 * y);
//btn.Dock = DockStyle.Fill;
y++;
count++;
Controls.Add(btn);
}
}
}
Unfortunately this does not apply any buttons to the form.
In addition I was wondering how could I append these buttons in a panel called subPanelClient
This worked for me, the issue was the position of the button, as you have to indicate it within a panel or form.
In this case i just docked them to the panel
private void updateClientListUI()
{
if (this.InvokeRequired)
{
this.Invoke(new MethodInvoker(this.updateClientListUI));
}
else
{
//Debug.WriteLine(clientNames[0]);
int basex = subPanelClient.Location.X;
int basey = subPanelClient.Location.Y;
subPanelClient.Controls.Clear();
Debug.WriteLine(clientNames.Count);
for (int i = 0; i < clientNames.Count; i++)
{
Button b = new Button();
b.Left = basex;
b.Top = basey;
b.Size = new Size(25, 25); // <== add this line
b.Dock = DockStyle.Top;
b.ForeColor = Color.Gainsboro;
b.FlatStyle = FlatStyle.Flat;
b.FlatAppearance.BorderSize = 0;
b.Padding = new Padding(35, 0, 0, 0);
b.TextAlign = ContentAlignment.MiddleLeft;
basey += 25;
b.Name = clientNames[i];
b.Text = clientNames[i];
subPanelClient.Controls.Add(b);
buttonsAdded.Insert(i, b);
}
}
}

Custom groupbox control not painting correctly when added to tabpage

I have a groupbox which I created a custom paint event for so that I
can control the border color.
It works great when the groupbox is on a form but when the groupbox is
on a tabpage, the control does not paint properly. Everything is blurry
and the child controls inside the groupbox are also blurry and get a border
drawn.
Any gentle help would be greatly appreciated!
Thanks,
Dan
using System.Drawing;
using System.Windows.Forms;
namespace CustomGroupBoxPaint
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
///////////////////////////////////////////////////////////////////////
private void groupBox_Paint(object sender, PaintEventArgs e)
{
// Default border line color
Color lineColor = Color.LightGray;
// Get the control
GroupBox gb = (GroupBox)sender;
// Figure out which color to use
if (gb.Enabled == true)
{
// User black line
lineColor = Color.Black;
}
else
{
// Use dark gray color
lineColor = Color.DarkGray;
}
//get the text size in groupbox
System.Drawing.Size tSize = TextRenderer.MeasureText(e.Graphics, gb.Text, gb.Font);
// Draw groupbox border
Rectangle borderRect = e.ClipRectangle;
borderRect.Y = (borderRect.Y + (tSize.Height / 2));
borderRect.Height = (borderRect.Height - (tSize.Height / 2));
ControlPaint.DrawBorder(e.Graphics, borderRect, lineColor, ButtonBorderStyle.Solid);
// Draw groupbox text
Rectangle textRect = e.ClipRectangle;
textRect.X = (textRect.X + 6);
textRect.Width = tSize.Width + 5;
textRect.Height = tSize.Height;
e.Graphics.FillRectangle(new SolidBrush(gb.BackColor), textRect);
TextRenderer.DrawText(e.Graphics, gb.Text, gb.Font, textRect, gb.ForeColor);
}
}
}
namespace CustomGroupBoxPaint
{
partial class Form1
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.tabControl1 = new System.Windows.Forms.TabControl();
this.tabPage1 = new System.Windows.Forms.TabPage();
this.groupBox2 = new System.Windows.Forms.GroupBox();
this.checkBox2 = new System.Windows.Forms.CheckBox();
this.groupBox1 = new System.Windows.Forms.GroupBox();
this.checkBox1 = new System.Windows.Forms.CheckBox();
this.tabPage2 = new System.Windows.Forms.TabPage();
this.groupBox3 = new System.Windows.Forms.GroupBox();
this.checkBox3 = new System.Windows.Forms.CheckBox();
this.groupBox4 = new System.Windows.Forms.GroupBox();
this.checkBox4 = new System.Windows.Forms.CheckBox();
this.tabControl1.SuspendLayout();
this.tabPage1.SuspendLayout();
this.groupBox2.SuspendLayout();
this.groupBox1.SuspendLayout();
this.groupBox3.SuspendLayout();
this.groupBox4.SuspendLayout();
this.SuspendLayout();
//
// tabControl1
//
this.tabControl1.Controls.Add(this.tabPage1);
this.tabControl1.Controls.Add(this.tabPage2);
this.tabControl1.Location = new System.Drawing.Point(40, 24);
this.tabControl1.Name = "tabControl1";
this.tabControl1.SelectedIndex = 0;
this.tabControl1.Size = new System.Drawing.Size(376, 352);
this.tabControl1.TabIndex = 0;
//
// tabPage1
//
this.tabPage1.Controls.Add(this.groupBox2);
this.tabPage1.Controls.Add(this.groupBox1);
this.tabPage1.Location = new System.Drawing.Point(4, 22);
this.tabPage1.Name = "tabPage1";
this.tabPage1.Padding = new System.Windows.Forms.Padding(3);
this.tabPage1.Size = new System.Drawing.Size(368, 326);
this.tabPage1.TabIndex = 0;
this.tabPage1.Text = "tabPage1";
this.tabPage1.UseVisualStyleBackColor = true;
//
// groupBox2
//
this.groupBox2.Controls.Add(this.checkBox2);
this.groupBox2.Enabled = false;
this.groupBox2.Location = new System.Drawing.Point(52, 168);
this.groupBox2.Name = "groupBox2";
this.groupBox2.Size = new System.Drawing.Size(272, 100);
this.groupBox2.TabIndex = 1;
this.groupBox2.TabStop = false;
this.groupBox2.Text = "DisabledGBTabPage";
this.groupBox2.Paint += new System.Windows.Forms.PaintEventHandler(this.groupBox_Paint);
//
// checkBox2
//
this.checkBox2.AutoSize = true;
this.checkBox2.Location = new System.Drawing.Point(64, 42);
this.checkBox2.Name = "checkBox2";
this.checkBox2.Size = new System.Drawing.Size(80, 17);
this.checkBox2.TabIndex = 1;
this.checkBox2.Text = "checkBox2";
this.checkBox2.UseVisualStyleBackColor = true;
//
// groupBox1
//
this.groupBox1.Controls.Add(this.checkBox1);
this.groupBox1.Location = new System.Drawing.Point(48, 32);
this.groupBox1.Name = "groupBox1";
this.groupBox1.Size = new System.Drawing.Size(272, 100);
this.groupBox1.TabIndex = 0;
this.groupBox1.TabStop = false;
this.groupBox1.Text = "EnabledGBTabPage";
this.groupBox1.Paint += new System.Windows.Forms.PaintEventHandler(this.groupBox_Paint);
//
// checkBox1
//
this.checkBox1.AutoSize = true;
this.checkBox1.Location = new System.Drawing.Point(64, 48);
this.checkBox1.Name = "checkBox1";
this.checkBox1.Size = new System.Drawing.Size(80, 17);
this.checkBox1.TabIndex = 0;
this.checkBox1.Text = "checkBox1";
this.checkBox1.UseVisualStyleBackColor = true;
//
// tabPage2
//
this.tabPage2.Location = new System.Drawing.Point(4, 22);
this.tabPage2.Name = "tabPage2";
this.tabPage2.Padding = new System.Windows.Forms.Padding(3);
this.tabPage2.Size = new System.Drawing.Size(368, 326);
this.tabPage2.TabIndex = 1;
this.tabPage2.Text = "tabPage2";
this.tabPage2.UseVisualStyleBackColor = true;
//
// groupBox3
//
this.groupBox3.Controls.Add(this.checkBox3);
this.groupBox3.Location = new System.Drawing.Point(512, 78);
this.groupBox3.Name = "groupBox3";
this.groupBox3.Size = new System.Drawing.Size(200, 100);
this.groupBox3.TabIndex = 1;
this.groupBox3.TabStop = false;
this.groupBox3.Text = "EnabledGBform";
this.groupBox3.Paint += new System.Windows.Forms.PaintEventHandler(this.groupBox_Paint);
//
// checkBox3
//
this.checkBox3.AutoSize = true;
this.checkBox3.Location = new System.Drawing.Point(60, 42);
this.checkBox3.Name = "checkBox3";
this.checkBox3.Size = new System.Drawing.Size(80, 17);
this.checkBox3.TabIndex = 1;
this.checkBox3.Text = "checkBox3";
this.checkBox3.UseVisualStyleBackColor = true;
//
// groupBox4
//
this.groupBox4.Controls.Add(this.checkBox4);
this.groupBox4.Enabled = false;
this.groupBox4.Location = new System.Drawing.Point(512, 238);
this.groupBox4.Name = "groupBox4";
this.groupBox4.Size = new System.Drawing.Size(200, 100);
this.groupBox4.TabIndex = 2;
this.groupBox4.TabStop = false;
this.groupBox4.Text = "DisabledGBform";
this.groupBox4.Paint += new System.Windows.Forms.PaintEventHandler(this.groupBox_Paint);
//
// checkBox4
//
this.checkBox4.AutoSize = true;
this.checkBox4.Location = new System.Drawing.Point(60, 42);
this.checkBox4.Name = "checkBox4";
this.checkBox4.Size = new System.Drawing.Size(80, 17);
this.checkBox4.TabIndex = 1;
this.checkBox4.Text = "checkBox4";
this.checkBox4.UseVisualStyleBackColor = true;
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(800, 450);
this.Controls.Add(this.groupBox4);
this.Controls.Add(this.groupBox3);
this.Controls.Add(this.tabControl1);
this.Name = "Form1";
this.Text = "Form1";
this.tabControl1.ResumeLayout(false);
this.tabPage1.ResumeLayout(false);
this.groupBox2.ResumeLayout(false);
this.groupBox2.PerformLayout();
this.groupBox1.ResumeLayout(false);
this.groupBox1.PerformLayout();
this.groupBox3.ResumeLayout(false);
this.groupBox3.PerformLayout();
this.groupBox4.ResumeLayout(false);
this.groupBox4.PerformLayout();
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.TabControl tabControl1;
private System.Windows.Forms.TabPage tabPage1;
private System.Windows.Forms.TabPage tabPage2;
private System.Windows.Forms.GroupBox groupBox2;
private System.Windows.Forms.GroupBox groupBox1;
private System.Windows.Forms.GroupBox groupBox3;
private System.Windows.Forms.GroupBox groupBox4;
private System.Windows.Forms.CheckBox checkBox2;
private System.Windows.Forms.CheckBox checkBox1;
private System.Windows.Forms.CheckBox checkBox3;
private System.Windows.Forms.CheckBox checkBox4;
}
}
Screen shot showing problem

Custom MessageBox with custom-defined Buttons [duplicate]

I am doing C# application, and I want to change the style of a message box. Is it possible or not?
Example: change button style, fore color, etc.
You can't restyle the default MessageBox as that's dependant on the current Windows OS theme, however you can easily create your own MessageBox. Just add a new form (i.e. MyNewMessageBox) to your project with these settings:
FormBorderStyle FixedToolWindow
ShowInTaskBar False
StartPosition CenterScreen
To show it use myNewMessageBoxInstance.ShowDialog();. And add a label and buttons to your form, such as OK and Cancel and set their DialogResults appropriately, i.e. add a button to MyNewMessageBox and call it btnOK. Set the DialogResult property in the property window to DialogResult.OK. When that button is pressed it would return the OK result:
MyNewMessageBox myNewMessageBoxInstance = new MyNewMessageBox();
DialogResult result = myNewMessageBoxInstance.ShowDialog();
if (result == DialogResult.OK)
{
// etc
}
It would be advisable to add your own Show method that takes the text and other options you require:
public DialogResult Show(string text, Color foreColour)
{
lblText.Text = text;
lblText.ForeColor = foreColour;
return this.ShowDialog();
}
MessageBox::Show uses function from user32.dll, and its style is dependent on Windows, so you cannot change it like that, you have to create your own form
Here is the code needed to create your own message box:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace MyStuff
{
public class MyLabel : Label
{
public static Label Set(string Text = "", Font Font = null, Color ForeColor = new Color(), Color BackColor = new Color())
{
Label l = new Label();
l.Text = Text;
l.Font = (Font == null) ? new Font("Calibri", 12) : Font;
l.ForeColor = (ForeColor == new Color()) ? Color.Black : ForeColor;
l.BackColor = (BackColor == new Color()) ? SystemColors.Control : BackColor;
l.AutoSize = true;
return l;
}
}
public class MyButton : Button
{
public static Button Set(string Text = "", int Width = 102, int Height = 30, Font Font = null, Color ForeColor = new Color(), Color BackColor = new Color())
{
Button b = new Button();
b.Text = Text;
b.Width = Width;
b.Height = Height;
b.Font = (Font == null) ? new Font("Calibri", 12) : Font;
b.ForeColor = (ForeColor == new Color()) ? Color.Black : ForeColor;
b.BackColor = (BackColor == new Color()) ? SystemColors.Control : BackColor;
b.UseVisualStyleBackColor = (b.BackColor == SystemColors.Control);
return b;
}
}
public class MyImage : PictureBox
{
public static PictureBox Set(string ImagePath = null, int Width = 60, int Height = 60)
{
PictureBox i = new PictureBox();
if (ImagePath != null)
{
i.BackgroundImageLayout = ImageLayout.Zoom;
i.Location = new Point(9, 9);
i.Margin = new Padding(3, 3, 2, 3);
i.Size = new Size(Width, Height);
i.TabStop = false;
i.Visible = true;
i.BackgroundImage = Image.FromFile(ImagePath);
}
else
{
i.Visible = true;
i.Size = new Size(0, 0);
}
return i;
}
}
public partial class MyMessageBox : Form
{
private MyMessageBox()
{
this.panText = new FlowLayoutPanel();
this.panButtons = new FlowLayoutPanel();
this.SuspendLayout();
//
// panText
//
this.panText.Parent = this;
this.panText.AutoScroll = true;
this.panText.AutoSize = true;
this.panText.AutoSizeMode = AutoSizeMode.GrowAndShrink;
//this.panText.Location = new Point(90, 90);
this.panText.Margin = new Padding(0);
this.panText.MaximumSize = new Size(500, 300);
this.panText.MinimumSize = new Size(108, 50);
this.panText.Size = new Size(108, 50);
//
// panButtons
//
this.panButtons.AutoSize = true;
this.panButtons.AutoSizeMode = AutoSizeMode.GrowAndShrink;
this.panButtons.FlowDirection = FlowDirection.RightToLeft;
this.panButtons.Location = new Point(89, 89);
this.panButtons.Margin = new Padding(0);
this.panButtons.MaximumSize = new Size(580, 150);
this.panButtons.MinimumSize = new Size(108, 0);
this.panButtons.Size = new Size(108, 35);
//
// MyMessageBox
//
this.AutoScaleDimensions = new SizeF(8F, 19F);
this.AutoScaleMode = AutoScaleMode.Font;
this.ClientSize = new Size(206, 133);
this.Controls.Add(this.panButtons);
this.Controls.Add(this.panText);
this.Font = new Font("Calibri", 12F, FontStyle.Regular, GraphicsUnit.Point, ((byte)(0)));
this.FormBorderStyle = FormBorderStyle.FixedSingle;
this.Margin = new Padding(4);
this.MaximizeBox = false;
this.MinimizeBox = false;
this.MinimumSize = new Size(168, 132);
this.Name = "MyMessageBox";
this.ShowIcon = false;
this.ShowInTaskbar = false;
this.StartPosition = FormStartPosition.CenterScreen;
this.ResumeLayout(false);
this.PerformLayout();
}
public static string Show(Label Label, string Title = "", List<Button> Buttons = null, PictureBox Image = null)
{
List<Label> Labels = new List<Label>();
Labels.Add(Label);
return Show(Labels, Title, Buttons, Image);
}
public static string Show(string Label, string Title = "", List<Button> Buttons = null, PictureBox Image = null)
{
List<Label> Labels = new List<Label>();
Labels.Add(MyLabel.Set(Label));
return Show(Labels, Title, Buttons, Image);
}
public static string Show(List<Label> Labels = null, string Title = "", List<Button> Buttons = null, PictureBox Image = null)
{
if (Labels == null) Labels = new List<Label>();
if (Labels.Count == 0) Labels.Add(MyLabel.Set(""));
if (Buttons == null) Buttons = new List<Button>();
if (Buttons.Count == 0) Buttons.Add(MyButton.Set("OK"));
List<Button> buttons = new List<Button>(Buttons);
buttons.Reverse();
int ImageWidth = 0;
int ImageHeight = 0;
int LabelWidth = 0;
int LabelHeight = 0;
int ButtonWidth = 0;
int ButtonHeight = 0;
int TotalWidth = 0;
int TotalHeight = 0;
MyMessageBox mb = new MyMessageBox();
mb.Text = Title;
//Image
if (Image != null)
{
mb.Controls.Add(Image);
Image.MaximumSize = new Size(150, 300);
ImageWidth = Image.Width + Image.Margin.Horizontal;
ImageHeight = Image.Height + Image.Margin.Vertical;
}
//Labels
List<int> il = new List<int>();
mb.panText.Location = new Point(9 + ImageWidth, 9);
foreach (Label l in Labels)
{
mb.panText.Controls.Add(l);
l.Location = new Point(200, 50);
l.MaximumSize = new Size(480, 2000);
il.Add(l.Width);
}
int mw = Labels.Max(x => x.Width);
il.ToString();
Labels.ForEach(l => l.MinimumSize = new Size(Labels.Max(x => x.Width), 1));
mb.panText.Height = Labels.Sum(l => l.Height);
mb.panText.MinimumSize = new Size(Labels.Max(x => x.Width) + mb.ScrollBarWidth(Labels), ImageHeight);
mb.panText.MaximumSize = new Size(Labels.Max(x => x.Width) + mb.ScrollBarWidth(Labels), 300);
LabelWidth = mb.panText.Width;
LabelHeight = mb.panText.Height;
//Buttons
foreach (Button b in buttons)
{
mb.panButtons.Controls.Add(b);
b.Location = new Point(3, 3);
b.TabIndex = Buttons.FindIndex(i => i.Text == b.Text);
b.Click += new EventHandler(mb.Button_Click);
}
ButtonWidth = mb.panButtons.Width;
ButtonHeight = mb.panButtons.Height;
//Set Widths
if (ButtonWidth > ImageWidth + LabelWidth)
{
Labels.ForEach(l => l.MinimumSize = new Size(ButtonWidth - ImageWidth - mb.ScrollBarWidth(Labels), 1));
mb.panText.Height = Labels.Sum(l => l.Height);
mb.panText.MinimumSize = new Size(Labels.Max(x => x.Width) + mb.ScrollBarWidth(Labels), ImageHeight);
mb.panText.MaximumSize = new Size(Labels.Max(x => x.Width) + mb.ScrollBarWidth(Labels), 300);
LabelWidth = mb.panText.Width;
LabelHeight = mb.panText.Height;
}
TotalWidth = ImageWidth + LabelWidth;
//Set Height
TotalHeight = LabelHeight + ButtonHeight;
mb.panButtons.Location = new Point(TotalWidth - ButtonWidth + 9, mb.panText.Location.Y + mb.panText.Height);
mb.Size = new Size(TotalWidth + 25, TotalHeight + 47);
mb.ShowDialog();
return mb.Result;
}
private FlowLayoutPanel panText;
private FlowLayoutPanel panButtons;
private int ScrollBarWidth(List<Label> Labels)
{
return (Labels.Sum(l => l.Height) > 300) ? 23 : 6;
}
private void Button_Click(object sender, EventArgs e)
{
Result = ((Button)sender).Text;
Close();
}
private string Result = "";
}
}

Restrict the numbers of controls in a winform

i have a button in my form and for every button click it is adding groupBox. but i want a winform contain only 8 groupboxes. when the numbers of groupBox reach 8 it will automatically do Visible=false all 8 before groupBox and again adds a groupBox named(groupBox9). what must i do?
private void butonYeni_Click(object sender, EventArgs e)
{
//creating Font
Font font = new Font("Microsoft Sans Serif", 10.0f, FontStyle.Bold);
Font font2 = new Font("Microsoft Sans Serif", 9.0f, FontStyle.Bold);
int sayGB = 0;
foreach (Control c in this.Controls)
{
if (c.GetType() == typeof(GroupBox))
{
sayGB++;
}
for (int i = sayGB; i < 1000; i++)
{
//creating groupbox
GroupBox Group = new GroupBox();
Group.Width = 767;
Group.Height = 179;
Group.Text = "Soru & Cevap";
Group.Font = font;
Group.ForeColor = Color.Maroon;
Group.Location = new Point(200,66);
//creating label
Label Soru = new Label();
Soru.Text = "Soru: ";
Soru.Font = font2;
Soru.ForeColor = Color.Maroon;
Soru.Location = new Point(6,33);
Soru.Width = 53;
Soru.Height = 13;
//creating textbox
TextBox soruText = new TextBox();
soruText.Width = 685;
soruText.Height = 20;
soruText.Font = font2;
soruText.ForeColor = Color.Black;
soruText.Multiline = true;
soruText.Location = new Point(70,31);
//creating label
Label Cevap = new Label();
Cevap.Text = "Cevap:";
Cevap.Font = font2;
Cevap.ForeColor = Color.Maroon;
Cevap.Location = new Point(6, 92);
Cevap.Width = 53;
Cevap.Height = 25;
//creating textbox
TextBox cevapText = new TextBox();
cevapText.Width = 685;
cevapText.Height = 69;
cevapText.Font = font2;
cevapText.ForeColor = Color.Black;
cevapText.Multiline = true;
cevapText.Location = new Point(70,67);
//creating button
Button btn = new Button();
btn.Width = 75;
btn.Height = 25;
btn.Text = "Kaydet";
btn.BackColor = Color.Maroon;
btn.Font = font2;
btn.ForeColor = Color.White;
btn.Location = new Point(682,148);
//kontrolleri ekleme
Group.Controls.Add(btn);
Group.Controls.Add(Soru);
Group.Controls.Add(soruText);
Group.Controls.Add(Cevap);
Group.Controls.Add(cevapText);
this.Controls.Add(Group);
}
}
}
define an integer class variable and increase it everytime the button is clicked. After increasing it, check if it's greater than 8. If it is, set your stuff to Visible = false.
Mock up:
public class MyClass
{
private int groupboxCounter = 0;
public MyClass()
{
}
private void btn_click(...)
{
// add a new groupbox here
groupboxCounter++;
if (groupboxCounter > 8)
{
//make stuff invisible here
}
}
}

TableLayoutPanel changing it's sizing

I have a few tablelayoutpanels in my program in order to lay out different controls in rows. Until recently these were all working correctly, but after a change in server this is no longer the case. A potential cause is a change in screen resolution as I noticed similar problems on other computers running my program.
An example of this problem is shown below
Before the data rows are loaded (from database), the sizing is incorrect. A measurement using the VS designer shows that the size in figure 2 is correct. Interestingly, if I add a blank row to this table then the resizing doesn't happen.
public JobOpMainTable()
{
DoubleBuffered = true;
AutoSize = true;
AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink;
DoubleBuffered = true;
BackColor = Color.White;
CellBorderStyle = TableLayoutPanelCellBorderStyle.Single;
headers();
}
private void headers()
{
string[] names = { "Operation", "Est Lab Hrs", "Est UM Hrs", "Act Lab Hrs", "Act UM Hrs" };
for (int i = 0; i < names.Length; i++) header(names[i], i);
}
private void header(string name, int col)
{
Panel pan = new Panel();
pan.Width = widths[col];
pan.Height = 25;
pan.BackColor = Color.Black;
pan.Dock = DockStyle.Fill;
pan.Margin = new System.Windows.Forms.Padding(0);
TextBox txt = new TextBox();
txt.Font = new System.Drawing.Font("Microsoft sans serif", 8, FontStyle.Bold);
txt.Text = name;
txt.ReadOnly = true;
txt.BackColor = Color.Black;
txt.ForeColor = Color.White;
txt.Dock = DockStyle.Fill;
txt.BorderStyle = System.Windows.Forms.BorderStyle.None
pan.Controls.Add(txt);
Controls.Add(pan, col, 0);
}
private int newRow()
{
int row = Controls.Count / 5;
for (int i = 0; i <= 4; i++)
{
TextBox txt = new TextBox();
txt.Width = widths[i];
txt.BackColor = Color.White;
txt.BorderStyle = System.Windows.Forms.BorderStyle.None;
txt.ReadOnly = true;
txt.Dock = DockStyle.Fill;
txt.Margin = new Padding(0);
txt.Enter += new EventHandler(enterCell);
txt.Leave += new EventHandler(leaveCell);
Controls.Add(txt, i, row);
}
return row;
}
Above is the code I believe is relevant to the problem. The resizing occurs the first time newRow() is called when loading in data: each new box makes the column wider. Again though, the odd thing is this doesn't occur if I add a row from the constructor

Categories