How to automaticly locate buttons on panel c# - c#

I have a few buttons to add on the form. In the code I'm setting up some button properties:
class DigitButton : Button
{
private static int digitBtnTag;
public DigitButton()
: base()
{
this.Size = new Size(30, 30);
this.Tag = digitBtnTag;
this.Text = (this.Tag).ToString();
this.Margin = new Padding(2);
this.Padding = new Padding(2);
digitBtnTag++;
}
}
In the MainForm.cs I have
for (int i = 0; i < dgtBtns.Length; i++)
{
dgtBtns[i] = new DigitButton();
dgtBtns[i].Click += new EventHandler(this.digitButtonClick);
digitPanel.Controls.Add(dgtBtns[i]);
}
So when I launch a program I see all my buttons in the one place: (0;0) on digitPanel despite property Margin. So why don't all these buttons automaticly "push" each other in the different directions? And how to make it?

Have you tried using a FlowLayout Panel ?
Also, this video might help:
Windows Forms Controls Lesson 5: How to use the FlowLayout Panel

that's not the way controls works in c#. i'm guessing you programed at java a bit because the layout in jave works that whay, but in c# just do
for (int i = 0; i < dgtBtns.Length; i++)
{
dgtBtns[i] = new DigitButton();
dgtBtns[i].Location = new Point(50, 50 * i); // Multiplying by i makes the location shift in every loop
dgtBtns[i].Click += new EventHandler(this.digitButtonClick);
digitPanel.Controls.Add(dgtBtns[i]);
}
you'll have to figure out the location parameters by trying and see

You need to define Left and Top then add the button height or width each time you loop to position your buttons correctly i.e.
int bTop=0;
int bLeft=0;
for (int i = 0; i < dgtBtns.Length; i++)
{
dgtBtns[i] = new DigitButton();
dgtBtns[i].Click += new EventHandler(this.digitButtonClick);
dgtBtns[i].Top = bTop;
bTop += dgtBtns[i].Height;
digitPanel.Controls.Add(dgtBtns[i]);
}

Related

How to create dynamically C# panels

I create a contact manager. The user can already enter some and they are stored in a file and re-opened when the program is started. Each contact is an object of my Person class.
When launching the program (in Load()) I created a for loop until all contacts have been explored (contacts are stored when opened in a Person table)
So now I come to my problem:
I have a panel that is scrollable (I have enabled the option) and I would like every 50 pixels in height, that a new panel is created with name, first name, email and phone number of my contacts and a pictureBox.
Except, I would like to be able to do it dynamically instead of creating the same thing more than 50 times and repeating the same code 50 times
Because for the moment I have done this:
for(int i = 0; i < contacts.Count; i++) //Afficher les contacts
{
if(!panel_contact1.Visible)
{
panel_contact1.Visible = true;
label_prenom_nom1.Text = contacts[i].Prenom + " " + contacts[i].Nom;
label_email1.Text = contacts[i].mail;
label_tel1.Text = contacts[i].tel;
pictureBox1.Image = Image.FromFile(contacts[i].pathImage);
}
else if(!panel_contact2.Visible)
{
panel_contact2.Visible = true;
label_prenom_nom2.Text = contacts[i].Prenom + " " + contacts[i].Nom;
label_email2.Text = contacts[i].mail;
label_tel2.Text = contacts[i].tel;
pictureBox2.Image = Image.FromFile(contacts[i].pathImage);
}
}
It's the code only for the first two contacts and I don't want to repeat it up to 100 times.
So my question is:
How to create panels, with in each of the labels and a pictureBox, every 50px in a panel.
Thank you for reading, if you just have advice said always the same if you all have the code I'm a taker especially since I think it should be easy to do because the content of the labels are already dynamically teaching.
Thank you.
On WinForms, you can use this:
int x = 0;
int y = 0;
int delta = 10;
for ( int i = 0; i < contacts.Count; i++ )
{
// Create picture box
var picture = new PictureBox();
picture.Image = Image.FromFile(contacts[i].pathImage);
picture.Location = new Point(x, y);
picture.Size = new Size(picture.Image.Width, picture.Image.Height);
int dx = picture.Width + delta;
// Create name label
var labelName = new Label();
labelName.AutoSize = true;
labelName.Location = new Point(x + dx, y);
labelName.Font = new Font(labelName.Font, FontStyle.Bold);
labelName.Text = contacts[i].Prenom + " " + contacts[i].Nom;
// Create mail label
var labelMail = new Label();
labelMail.AutoSize = true;
labelMail.Location = new Point(x + dx, y + labelName.Height);
labelMail.Text = contacts[i].mail;
// Create phone label
var labelPhone = new Label();
labelPhone.AutoSize = true;
labelPhone.Location = new Point(x + dx, y + labelName.Height + labelMail.Height);
labelPhone.Text = contacts[i].tel;
// Add controls
panel.Controls.Add(picture);
panel.Controls.Add(labelName);
panel.Controls.Add(labelMail);
panel.Controls.Add(labelPhone);
// Iterate
int dy1 = labelName.Height + labelMail.Height + labelPhone.Height;
int dy2 = picture.Height;
y += Math.Max(dy1, dy2) + delta;
}
But you may prefer create a custom control where you put a picture box and three labels designed as you want with colors, font size, bolding, margin, borderstyle and so on, with Height at 50.
Add new user custom control with Project > Add > User control and choose a file name like PersonControl.
public partial class PersonControl : UserControl
{
public PersonControl()
{
InitializeComponent();
}
public PersonControl(Person person) : this()
{
pictureBox.Image = Image.FromFile(person.pathImage);
labelName.Text = person.Prenom + " " + person.Nom;
labelMail.Text = person.mail;
labelPhone.Text = person.tel;
}
}
int x = 0;
int y = 0;
for ( int i = 0; i < contacts.Count; i++ )
{
var control = new PersonControl(contacts[i]);
control.Location = new Point(x, y);
panel.Controls.Add(control);
y += control.Height;
}
You should take care of the file image size that must be the same for all and the same as the picture box else you need to manage that by resizing for example.
How to resize an Image C#
If you're using windows forms, create a user control with a constructor using the Person object, set the labels and picture boxes to the info of that person. In the main loop you posted, create a new instance of this and set it's position to 0, i * 50 to place it under the previous one.
Example:
for(int i = 0; i < contacts.Count; i++)
{
YourUserControl u1 = new YourUserControl(pass the person object);
Panel1.Controls.Add(u1);
u1.Location = new Point(0, i * 50);
}
This depends on the display technolgy you are using (WinForms, WPF/UWP, ASP.NET, other).
In Windows Forms you just create the elements and add them to the container. The designer wroks on it's own part of the partial class. The designer code is run with InitializeComponents() in the constructor. Anything it can do, you can do. And you can easily look at it.
In WPF/UWP stuff is a bit more complicated. The designer does not work on code, but on XAML, a dedciated markup language. You are not supposed to manually add anything to the UI from the code. WPF/UWP and XAML were designed with the MVVM pattern in mind. And dealing with lists of things is what it does best. While you can use other patterns, generally that looses 90% of it's power and runs into issues at every other corner.
For ASP.Net it would depend on wich pattern you use. While not originally designed for it, MVC has been extremely popular with WebApplication. So much so, it is almost synonimous with WebApplications and ASP.NET. However this does not look like a web Application.

Adding a control to another control which is created at runtime

I am trying to add a picturebox control to a panel which is created at runtime.
It is for a chess game I am working on. I want to add a picture box to each panel , an assigning the image to the control later. Here is what I have so far:
//Sets the number of rows on the chess board
for (int i = 0; i < 8; i++)
{
//Set the number of columns on the board
for (int j = 0; j < 8; j++)
{
ChessSquare sq = new ChessSquare(((char)(65 + i)).ToString(), 7- j);
sq.Color = (i + (j % 2)) % 2 == 0 ? Color.Black : Color.White;
Panel p = new Panel()
{
Size = new Size(blockSize, blockSize),
BackColor = sq.Color,
Tag = sq,
Location = new Point(blockSize * i + 15, blockSize * j + 15),
BackgroundImageLayout = ImageLayout.Stretch
};
p.MouseEnter += new EventHandler(squareMouseEnter);
p.MouseLeave += new EventHandler(squareMouseLeave);
p.Click += new EventHandler(squareMouseClick);
chessBoardPanels[i, j] = p;
groupBox1.Controls.Add(p);
}
}
//SetUp Board
SetUpBoad Setup = new SetUpBoad();
SetUpBoad(chessBoardPanels);
Since you already put the Panels into the panel-array (?)
chessBoardPanels[i, j] = p;
You can add the PictureBoxes either now or later..:
PictureBox pb = new PictureBox ();
pb.Size = ..
pb.BackColor = Color.Transparent;
chessBoardPanels[i,j].Controls.Add(pb);
To access them later you can cast their first Control to PictureBox:
PictureBox pb = (PictureBox)chessBoardPanels[i,j].Controls[0];
pb.Image = aQueenImage;
If you want to add a PictureBox only where a piece is you need to do checks:
if (chessBoardPanels[i,j].Controls.Count > 0)
{
PictureBox pb = (PictureBox)chessBoardPanels[i,j].Controls[0];
pb.Image = aQueenImage;
}
To move a piece from <i1,j1> to <i2, j2> you do as expected:
chessBoardPanels[i1,j1].Controls[0].Parent = chessBoardPanels[i2,j2];
I notice that you are hooking up mouse events. If you want to use them to move the pieces, remember that transparency will not work for overlapping controls in Winforms and so while a piece-Box is crossing Panels it will not have working tranparency around the Image.
While the pBox is nested in a Panel all is well but to move it you would have to first make it a child of the parent of those panels and only add it to the target Panel upon MouseUp; the coordinate corrections can be solved but the tranparency, if you need it, will be a bigger problem..
The usual advice it to consider drawing at least those board squares and maybe even the pieces onto a base board-Panel (or board-PictureBox)

Create dynamic buttons in a grid layout - Create a magic square UI

I'm supposed to create a magic square in 2D using Windows Forms Application. It should look like this:
However, the user should be able to decide the size of the square (3x3, 5x5, 7x7, etc). I already wrote the code in a Console Application, but I don't know how to add the 2D graphics.
Somebody already asked this question (How do I put my result into a GUI?), and one of the answers was to use DataGridView, but I'm not sure if that's what I'm looking for, since I can't make it look like the picture.
Any ideas or advice?
You can use a TableLayoutPanel and add buttons to panel dynamically.
If you don't need interaction with buttons, you can add Label instead.
Create square dynamically:
public void CreateSquare(int size)
{
//Remove previously created controls and free resources
foreach (Control item in this.Controls)
{
this.Controls.Remove(item);
item.Dispose();
}
//Create TableLayoutPanel
var panel = new TableLayoutPanel();
panel.RowCount = size;
panel.ColumnCount = size;
panel.BackColor = Color.Black;
//Set the equal size for columns and rows
for (int i = 0; i < size; i++)
{
var percent = 100f / (float)size;
panel.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, percent));
panel.RowStyles.Add(new RowStyle(SizeType.Percent, percent));
}
//Add buttons, if you have your desired output in an array
//you can set the text of buttons from your array
for (var i = 0; i < size; i++)
{
for (var j = 0; j < size; j++)
{
var button = new Button();
button.BackColor = Color.Lime;
button.Font = new Font(button.Font.FontFamily, 20, FontStyle.Bold);
button.FlatStyle = FlatStyle.Flat;
//you can set the text of buttons from your array
//For example button.Text = array[i,j].ToString();
button.Text = string.Format("{0}", (i) * size + j + 1);
button.Name = string.Format("Button{0}", button.Text);
button.Dock = DockStyle.Fill;
//If you need interaction with buttons
button.Click += b_Click;
panel.Controls.Add(button, j, i);
}
}
panel.Dock = DockStyle.Fill;
this.Controls.Add(panel);
}
If you need interaction with buttons
void button_Click(object sender, EventArgs e)
{
var button = (Button)sender;
//Instead put your logic here
MessageBox.Show(string.Format("You clicked {0}", button.Text));
}
As an example, you can call
CreateSquare(3);
Screenshot:
You can create a Form and add a TableLayoutPanel with this property
tableLayoutPanel1.Dock = DockStyle.Fill;
tableLayoutPanel1.BackColor = Color.Gold;
and this is the result
When you create Row and Column, to fit correctly set the percentage in this way:
After this you can add a Button or Label in each square.

How to call a method from programmatically created buttons with different parameters?

my problem is how to call a existing method from another object with button specific parameters.
This is the method I need to call ( from MainWindow):
partial class Sidebar : Window
{
[...]
internal void SetPosition(System.Drawing.Rectangle workingarea, bool left)
{
Overlay.Properties.Settings.Default.SidebarSide = left;
Overlay.Properties.Settings.Default.Top = this.Top = workspace.Top;
Overlay.Properties.Settings.Default.Left = this.Left = workspace.Left;
Overlay.Properties.Settings.Default.Save();
this.Height = workspace.Height;
this.Width = workspace.Width;
timeGrid.Style = gridStyle;
Refresh();
}
[...]
}
and following is the method for creating buttons (and more) for each Screen connected to the machine
class SettingsWindow : Window
{
[...]
private void SidebarTab_Initialized(object sender, EventArgs e)
{
Canvas monitorCanvas = new Canvas();
spPosition.Children.Add(monitorCanvas);
System.Windows.Forms.Screen currentScreen = System.Windows.Forms.Screen.FromHandle(
new System.Windows.Interop.WindowInteropHelper(this).Handle);
System.Windows.Forms.Screen[] screens = System.Windows.Forms.Screen.AllScreens;
Point min = new Point(0,0);
Point max = new Point(0,0);
for (int i = 0; i < screens.Length; i++)
{
min.X = min.X < screens[i].Bounds.X ? min.X : screens[i].Bounds.X;
min.Y = min.Y < screens[i].Bounds.Y ? min.Y : screens[i].Bounds.Y;
max.X = max.X > (screens[i].Bounds.X + screens[i].Bounds.Width) ? max.X : (screens[i].Bounds.X + screens[i].Bounds.Width);
max.Y = max.Y > (screens[i].Bounds.Y + screens[i].Bounds.Height) ? max.Y : (screens[i].Bounds.Y + screens[i].Bounds.Height);
}
[...]
for (int i = 0; i < screens.Length; i++)
{
Border monitor = new Border();
monitor.BorderBrush = Brushes.Black;
monitor.BorderThickness = new Thickness(1);
Canvas.SetTop(monitor, (screens[i].Bounds.Top - min.Y) / scale);
Canvas.SetLeft(monitor, (screens[i].Bounds.Left - min.X) / scale);
monitor.Width = screens[i].Bounds.Width / scale;
monitor.Height = screens[i].Bounds.Height / scale;
DockPanel dp = new DockPanel();
Button monLeft = new Button();
monLeft.Width = scale;
DockPanel.SetDock(monLeft, Dock.Left);
Button monRight = new Button();
monRight.Width = scale;
DockPanel.SetDock(monRight, Dock.Right);
[...]
}
}
}
As you see, I need two buttons for every screen on the machine.
monLeft.Click = SetPosition(screens[i].WorkingArea, true); and
monRight.Click = SetPosition(screens[i].WorkingArea, true); is what I need.
Thanks in advance.
Use a lambda to define the event handler. This allows you to close over the local variable(s) that you'll need in your handler.
Note that closures close over variables, not values, so you don't want to close over i (it won't be the value that you want it to be by the time the event fires). You'll need to make a copy of the loop variable inside of the loop so that you can close over that instead. Well, that or use a foreach loop (in C# 5.0+) instead of a for loop.
foreach(var screen in screens)
{
//...
Button monRight = new Button();
monRight.Width = scale;
DockPanel.SetDock(monRight, Dock.Right);
monRight.Click += (s,e) => SetPosition(screen.WorkingArea, true);
}
Well, as you can see in http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.button.click(v=vs.110).aspx, Button.Click is an event, so you need to assign an event handler to it:
Either you wrap your SetPosition() method in an event handler and assign the event handler of your Button.Click event to it, or you can do it through lambda construction as suggested in the previous answer.
Another alternative is setting the Button.Command for your buttons, by implementing an instance of ICommand that will call the SetPosition() method.

Performance issue when adding controls to a panel in C#

I am creating a panel and then adding some labels/buttons to it to form a grid. The issue is that if I add more than say 25x25 items to the panel, there is a terrible performance hit. I can resize the form ok but when I scroll the panel to see all the labels the program lags, the labels/buttons tear or flicker, and sometimes it can make the program unresponsive. I have tried adding the controls to a "DoubleBufferedPanel" that I created. This seems to have no effect. What else could I do? Sorry for such a large code listing. I didn't want to waste anyone's time.
namespace GridTest
{
public partial class Form1 : Form
{
private const int COUNT = 50;
private const int SIZE = 50;
private Button[,] buttons = new Button[COUNT, COUNT];
private GridPanel pnlGrid;
public Form1()
{
InitializeComponent();
pnlGrid = new GridPanel();
pnlGrid.AutoScroll = true;
pnlGrid.Dock = DockStyle.Fill;
pnlGrid.BackColor = Color.Black;
this.Controls.Add(pnlGrid);
}
private void Form1_Load(object sender, EventArgs e)
{
int x = 0;
int y = 0;
int offset = 1;
for (int i = 0; i < COUNT; i++)
{
for (int j = 0; j < COUNT; j++)
{
buttons[i, j] = new Button();
buttons[i, j].Size = new Size(SIZE, SIZE);
buttons[i, j].Location = new Point(x, y);
buttons[i, j].BackColor = Color.White;
pnlGrid.Controls.Add(buttons[i, j]);
x = x + SIZE + offset;
}
x = 0;
y = y + SIZE + offset;
}
}
}
}
Also, the GridPanel class:
namespace GridTest
{
public class GridPanel : Panel
{
public GridPanel()
: base()
{
this.DoubleBuffered = true;
this.ResizeRedraw = false;
}
}
}
If you must add controls at run time, based on some dynamic or changing value, you might want to consider creating an image on the fly, and capturing mouse click events on its picturebox. This would be much quicker and only have one control to draw rather than hundreds. You would lose some button functionality such as the click animation and other automatic properties and events; but you could recreate most of those in the generation of the image.
This is a technique I use to offer users the ability to turn on and off individual devices among a pool of thousands, when the location in a 2-dimensional space matters. If the arrangement of the buttons is unimportant, you might be better offering a list of items in a listview or combobox, or as other answers suggest, a datagridview with button columns.
EDIT:
An example showing how to add a graphic with virtual buttons. Very basic implementation, but hopefully you will get the idea:
First, some initial variables as preferences:
int GraphicWidth = 300;
int GraphicHeight = 100;
int ButtonWidth = 60;
int ButtonHeight = 20;
Font ButtonFont = new Font("Arial", 10F);
Pen ButtonBorderColor = new Pen(Color.Black);
Brush ButtonTextColor = new SolidBrush(Color.Black);
Generating the image:
Bitmap ControlImage = new Bitmap(GraphicWidth, GraphicHeight);
using (Graphics g = Graphics.FromImage(ControlImage))
{
g.Clear(Color.White);
for (int x = 0; x < GraphicWidth; x += ButtonWidth)
for (int y = 0; y < GraphicHeight; y += ButtonHeight)
{
g.DrawRectangle(ButtonBorderColor, x, y, ButtonWidth, ButtonHeight);
string ButtonLabel = ((GraphicWidth / ButtonWidth) * (y / ButtonHeight) + x / ButtonWidth).ToString();
SizeF ButtonLabelSize = g.MeasureString(ButtonLabel, ButtonFont);
g.DrawString(ButtonLabel, ButtonFont, ButtonTextColor, x + (ButtonWidth/2) - (ButtonLabelSize.Width / 2), y + (ButtonHeight/2)-(ButtonLabelSize.Height / 2));
}
}
pictureBox1.Image = ControlImage;
And responding to the Click event of the pictureBox:
// Determine which "button" was clicked
MouseEventArgs em = (MouseEventArgs)e;
Point ClickLocation = new Point(em.X, em.Y);
int ButtonNumber = (GraphicWidth / ButtonWidth) * (ClickLocation.Y / ButtonHeight) + (ClickLocation.X / ButtonWidth);
MessageBox.Show(ButtonNumber.ToString());
I think you won't be able to prevent flickering having 625 buttons (btw, windows) on the panel. If such layout is mandatory for you, try to use the DataGridView, bind it to a fake data source containing the required number of columns and rows and create DataGridViewButtonColumns in it. This should work much more better then your current result ...

Categories

Resources