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

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.

Related

How to use buttons and textbox created dynamically

i made a program that create many dynamic panel on button "ADD". The thing is that the name of the dynamic panel that have been created is by this way:
pArr[counter].Name = "panel" + (panel0.Controls.Count + 1);
And so on, so i guess the 5th panel would be named "panel5" if I'm right.
I added some buttons and a Textbox in these dynamically created panels. I don't understand how to use them. I have read a lot of posts in here about it but as its the first time I'm working with this kind of dynamic panels, its hard for me to understand. I found a lot of examples that seems to answer the question but I'm still confused about the names, how to controls buttons and/or textbox.
Per example, how will I set an Event from a button clicked from the 7th panel? It is complicated.
This is my code:
private void btnAdd_Click(object sender, EventArgs e)
{
Color color = ColorTranslator.FromHtml("#f0f0f0");
Color color2 = ColorTranslator.FromHtml("#4285f4");
System.Random R = new System.Random();
Panel p = new Panel();
Label lbl = new Label();
TextBox text = new TextBox();
Button btn = new Button();
Button btn2 = new Button();
Button btn3 = new Button();
int x = 100;
int y = 10;
int x2 = 300;
int y2 = 10;
int x3 = 380;
int y3 = 10;
int x4 = 20;
int y4 = 13;
int x5 = 500;
int y5 = 10;
int counter = 0;
Panel[] pArr = new Panel[25];
pArr[counter] = p;
pArr[counter].Name = "panel" + (panel0.Controls.Count + 1);
pArr[counter].BackColor = color;
pArr[counter].Size = new Size(panel0.ClientSize.Width, 40);
pArr[counter].BorderStyle = BorderStyle.Fixed3D;
pArr[counter].Dock = DockStyle.Top;
lbl.Text = "Name";
lbl.ForeColor = color2;
lbl.Font = new Font("Verdana", lbl.Font.Size);
lbl.Size = new Size(75, 20);
lbl.Location = new Point(x4, y4);
pArr[counter].Controls.Add(lbl);
text.Name = "txtBox" + (panel0.Controls.Count + 1);
text.Size = new Size(120, 20);
text.Location = new Point(x, y);
pArr[counter].Controls.Add(text);
btn.Name = "btnStart" + (panel0.Controls.Count + 1);
btn.Text = "Start";
btn.Font = new Font("Verdana", btn2.Font.Size);
btn.ForeColor = color2;
btn.Size = new Size(75, 20);
btn.Location = new Point(x2, y2);
pArr[counter].Controls.Add(btn);
btn2.Name = "btnStop" + (panel0.Controls.Count + 1);
btn2.Text = "Stop";
btn2.Font = new Font("Verdana", btn2.Font.Size);
btn2.ForeColor = color2;
btn2.Size = new Size(75, 20);
btn2.Location = new Point(x3, y3);
pArr[counter].Controls.Add(btn2);
btn3.Name = "btnClose" + (panel0.Controls.Count + 1);
btn3.Text = "Close";
btn3.Font = new Font("Verdana", btn3.Font.Size);
btn3.ForeColor = color2;
btn3.Size = new Size(75, 20);
btn3.Location = new Point(x5, y5);
pArr[counter].Controls.Add(btn3);
panel0.Controls.Add(pArr[counter]);
panel0.AutoScroll = false;
panel0.HorizontalScroll.Enabled = false;
panel0.HorizontalScroll.Visible = false;
panel0.HorizontalScroll.Maximum = 0;
panel0.AutoScroll = true;
counter++;
}
Can someone explain me how to control panels/buttons/textbox?
Give this a go:
public partial class UserControl2 : UserControl
{
public UserControl2()
{
InitializeComponent();
}
private void btnAdd_Click(object sender, EventArgs e)
{
var color = ColorTranslator.FromHtml("#f0f0f0");
var color2 = ColorTranslator.FromHtml("#4285f4");
var r = new System.Random();
var p = new Panel();
var lbl = new Label();
var pnlTxtBox = new TextBox();
var pnlBtnStart = new Button();
var pnlBtnStop = new Button();
var pnlBtnClose = new Button();
p.Name = "panel" + (panel0.Controls.Count + 1);
p.BackColor = color;
p.Size = new Size(panel0.ClientSize.Width, 40);
p.BorderStyle = BorderStyle.Fixed3D;
p.Dock = DockStyle.Top;
lbl.Text = "Name";
lbl.ForeColor = color2;
lbl.Font = new Font("Verdana", lbl.Font.Size);
lbl.Size = new Size(75, 20);
lbl.Location = new Point(20, 13);
p.Controls.Add(lbl);
pnlTxtBox.Name = "txtBox";
pnlTxtBox.Size = new Size(120, 20);
pnlTxtBox.Location = new Point(100, 10);
p.Controls.Add(pnlTxtBox);
pnlBtnStart.Name = "btnStart";
pnlBtnStart.Text = "Start";
pnlBtnStart.Font = new Font("Verdana", pnlBtnStart.Font.Size);
pnlBtnStart.ForeColor = color2;
pnlBtnStart.Size = new Size(75, 20);
pnlBtnStart.Location = new Point(300, 10);
pnlBtnStart.Click += (s,e) => StartWasClicked(pnlTxtBox);
p.Controls.Add(pnlBtnStart);
pnlBtnStop.Name = "btnStop";
pnlBtnStop.Text = "Stop";
pnlBtnStop.Font = new Font("Verdana", pnlBtnStop.Font.Size);
pnlBtnStop.ForeColor = color2;
pnlBtnStop.Size = new Size(75, 20);
pnlBtnStop.Location = new Point(380, 10);
p.Controls.Add(pnlBtnStop);
pnlBtnClose.Name = "btnClose";
pnlBtnClose.Text = "Close";
pnlBtnClose.Font = new Font("Verdana", pnlBtnClose.Font.Size);
pnlBtnClose.ForeColor = color2;
pnlBtnClose.Size = new Size(75, 20);
pnlBtnClose.Location = new Point(500, 10);
pnlBtnClose.Click += (s,e) => CloseWasClicked(p);
p.Controls.Add(pnlBtnClose);
panel0.Controls.Add(p);
panel0.AutoScroll = false;
panel0.HorizontalScroll.Enabled = false;
panel0.HorizontalScroll.Visible = false;
panel0.HorizontalScroll.Maximum = 0;
panel0.AutoScroll = true;
}
void StartWasClicked(TextBox tb){
MessageBox.Show(tb.Text);
}
void CloseWasClicked(Panel p){
p.Visible = false;
}
}
pArr needs to be a member of the class, not a local variable. Then you can simply access pArr with an index like any other array.
The panel doesn't even need a name. Names are only useful in the Visual Studio designer so that it can generate the .Designer.cs file with a variable name.
As for the events, just add an event handler with btn.Click += OnStartClick; as you would do for a button normally. In the function declaration, you will get object sender which identifies the button. You can then use Array.IndexOf() MSDN to get the index.
private void OnStartClick(object sender, EventArgs e)
{
var button = (Button) sender;
var panel = button.Parent;
var index = Array.IndexOf(pArr, panel);
...
}
Hokay, so on a comment elsewhere you said you want to
MessageBox.Show("Button name pressed: " + buttonName + " panel position number: " + panelPositionNb)
It means minimally you can have a code that looks like: (the second to last line is new)
btn.Name = "btnStart" + (panel0.Controls.Count + 1);
btn.Text = "Start";
btn.Font = new Font("Verdana", btn2.Font.Size);
btn.ForeColor = color2;
btn.Size = new Size(75, 20);
btn.Location = new Point(x2, y2);
btn.Click += (s, e) => MessageBox.Show($"Button name pressed: {btn.Name}");
pArr[counter].Controls.Add(btn);
Taking this apart:
btn.Click += (s, e) => MessageBox.Show($"Button name pressed: {btn.Name}");
.Click is the event of the button. An event is simply a "list of methods that have a particular signature", and when you say += you add a method to the "list of methods that shall be called when the event is raised". There's no defined order; you can add multiple different methods and they will be called, but not necessarily in any particular sequence. Click has a type of EventHandler which sets out the number and type of arguments any method must have in order to qualify as an handler for any event that is shaped like an EventHandler
+= we've covered; if there is an event on the left, then the thing on the right must be a method with a particular signature (dictated by the event signature) i.e. in the case of a button your method on the right must be shaped like an EventHandler which means it must have a first argument of type object and a second argument of type EventArgs. Your btnAdd_Click is an example of a method that conforms to those rules
(s, e) is a method signature header. Specifically it's a mini method that we call a lambda. The compiler looks at the event signature and knows that the first thing has to be object and the second has to be EventArgs; you only have to give names - the compiler will fill in the types. Actually because we don't even use the names of the arguments in the method code, we could just write (_, _) (in .net core+; framework might complain about duplicate names) here which means "no name; throw it away".. But if we did use the variable in the lambda method we'd have to give it a name. We could give them types too: (object s, EventArgs e) and it starts to look a lot like a normal method if we do; we don't add these because mostly we don't need to; the compiler can usually figure them out on its own
=> is the thing that separates a lambda method signature from the body
MessageBox.Show($"Button name pressed: {btn.Name}") is the body of the method; the thing that will happen when the button is clicked.
Doing a panel close one:
btn3.Name = "btnClose" + (panel0.Controls.Count + 1);
btn3.Text = "Close";
btn3.Font = new Font("Verdana", btn3.Font.Size);
btn3.ForeColor = color2;
btn3.Size = new Size(75, 20);
btn3.Location = new Point(x5, y5);
var pnl = pArr[counter];
btn3.Click += (s,e) => pnl.Visible = false;
pnl.Controls.Add(btn3);
Here we take the panel and capture it into a temporary variable. There are specific reasons for doing this, and it doesn't exactly apply to your code as written but I'm assuming at some point you'll upgrade this to use a loop; if we just did pArr[counter].Visible C# would take the resting value of counter as it was after all the looping is done, and hide that panel.. Any button would either cause an error, because counter would be off the end of the panels array, or some other wrong panel would hide.
We don't have to use these mini-methods (lambdas); we can pass this data around another way if you like..
Taking the example of the panel hide, because it's actually doing something interesting with the UI. Let's have a method that hides a panel that it finds in the Tag of the control in the sender:
private void HidePanelInTag(object sender, EventArgs e){
//get the sender as a button; we will only ever attach this code to buttons that have a Panel in their Tag
var b = sender as Button;
//get the Tag from the button and cast it to a panel
var p = b.Tag as Panel;
p.Visible = false;
}
Now we can tweak the loop that is creating the btn3 close buttons:
btn3.Name = "btnClose" + (panel0.Controls.Count + 1);
btn3.Text = "Close";
btn3.Font = new Font("Verdana", btn3.Font.Size);
btn3.ForeColor = color2;
btn3.Size = new Size(75, 20);
btn3.Location = new Point(x5, y5);
btn3.Tag = pArr[counter];
btn3.Click += HidePanelInTag;
pnl.Controls.Add(btn3);
We've stored the panel in the Tag - this varies for every button, a different Panel. The event handler attachment looks simpler too, because whereas a lambda has a full method (header, and body) defined on the line it is encountered, in more old fashioned terms the method definition is separated from its use:
btn3.Click += HidePanelInTag;
Remember before we said += separates an event on the left, from a method on the right; so long as the method on the right obeys the signature of the event, we're allowed to "add it to the list of methods that are called when the event is raised".
When the button is clicked, HidePanelInTag is called. Windows Forms automatically puts the control that is raising the event (the button) into the object sender argument. That's how we retrieve the Panel to hide; every button has a different Panel in its tag. If you click the 25th button, the sender is the 25th button, and the Tag is the 25th panel
End of the day there are loads of ways to skin this cat. For example you don't have to store a panel in a button's Tag.. You could even do some crazy like this:
btn3.Click += (s, e) => {
var b = s as Button;
var pname = b.Name.Replace("btnClose", "panel");
var p = panel0.Controls[pname];
p.Visible = false;
};
Get the button name, change it to be what the panels name is, find the panel by name, hide it... All in a multi-line lambda. That's kinda nasty, just treat it "for educational purposes" - ultimately all these buttons you make end up stored in tree of controls (your form has a penal that has panels that have buttons..) that can be searched, so "name" does have a use.. But we probably wouldn't use it for this approach.
The main take-away from this is that just like setting the name, the text, the position etc dynamically you also need to wire up the click events dynamically. That's done using event_name_here += event_handler_method_name_without_parentheses_here; in this regard methods aren't really any different from data variables in the way they're passed around by name
Passing Methods Around Like We Pass Data
Edit, following on from a comment below
You're comfortable with Properties:
btn3.Name = "btnClose" + (panel0.Controls.Count + 1);
Events are nearly exactly the same:
btn3.Click += (s,e) => pnl.Visible = false;
Let's have a table:
Property, btn3.Name
Event, btn3.Click
receives a string
receives a method
set with =
set with +=
can receive any string you want, for example "btnClose" + (panel0.Controls.Count + 1)
can receive any method you want, so long as the method has two arguments: an object and an EventArgs, for example (s,e) => pnl.Visible = false
Once you're happy that the following two things are essentially both methods, one called GetTime, and one without a name (because it doesn't need one):
(n) => "Hello " + n + ", the time is " + DateTime.Now;
public string GetTime(string n){
return "Hello " + n + ", the time is " + DateTime.Now;
}
the only mental block you might have, that we need to unblock, is this idea of "passing methods around like we pass data around".
Methods typically produce data when you call them, so you're used to using a method to produce data and assign data:
btn3.Text = GetGermanTranslationFor("Close");
That will call the method GetGermanTranslationFor passing in "Close", and the method returns "Schließen", then "Schließen" will be set as the text - that was all "passing data around"
But suppose a button had a MethodToCallToGetTheText property where instead of setting the data, we set the method to call to get the data and then button will call that method itself:
btn3.MethodToCallToGetTheText = GetGermanTranslationFor
There is no ( after the method name here; we don't want to call the method ourselves.. We want to give the method to the button so the button can call it.
This is what events are intended to do; a way of saying "here, when the click happens, call this method I'm giving you".
Microsoft can write a Button but they can't know what text I will put on it, so they provide a Text property and I set it myself
Microsoft can write a Button but they can't know what what code I'll run when the user clicks it so they just provide a facility where they say "put a method here, with these certain parameters, and we'll call it when the user clicks"
As it happens, Microsoft decided that the "put a method here" should actually be "put one or more methods here", which is why we use += to wire them up (because events are like a list of methods that you add to) but other than that, the theory is the same as setting a property; passing methods round like data is very useful

Setting LayoutTransform to RotateTransform for elements on a Canvas yields unexpected results

From within MainWindow ctor :
for(var i = 0; i <5; i++)
{
var button = new Button {};
button.LayoutTransform = new RotateTransform(i * 10);
button.Width = 300;
button.Height = 300;
TempCanvas.Children.Add(button);
}
This produces the following:
Please can someone explain why this is happening. I am expecting the 5 buttons to be rotated through the same point.
I did not want to RenderTransform as the graphics that I will be rendering would be drawn outside of the parent and not reflected in the measure.
The Canvas is the issue, unlike other contains it is not constrained in its physical size, it stretches out to infinity in all directions. Therefore it's rotation origin is not the canvas.width/2 by canvas.height/2.
If you repeat your code in a grid or dockpanel you will get the required result.
Do you want something like this:
Code:
for (var i = 0; i < 5; i++)
{
var button = new Button { };
//button.LayoutTransform = new RotateTransform(i * 10);
button.RenderTransform = new RotateTransform(i * 10);
button.Width = 300;
button.Height = 300;
button.Margin = new Thickness(200, 0, 0, 0);
TempCanvas.Children.Add(button);
}

How to automaticly locate buttons on panel 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]);
}

How to make dynamically added buttons clickable

I am creating a C# application which fetches data from a database, and dynamically creates 5 textBoxes and one button in a single row.
The number of rows present in the database equals the number of rows of textBoxes and buttons that are created.
I could successfully create the rows of textBoxes and buttons, the textBoxes are even capable of displaying data that is being fetched from the database.
My trouble however is that the button that is generated, does nothing when clicked, now that is not unexpected since i haven't created a handler to handle the click event. But i am confused on how to dynamically create the click even handler for the buttons that are again generated dynamically.
Below is the code sample that generated the textBoxes and buttons.
for (int i = 3; i <= count; i++)
{
com.Parameters[0].Value = i;
using (SqlCeDataReader rd = com.ExecuteReader())
if (rd.Read())
{
pname = (rd["pname"].ToString());
cname = (rd["cname"].ToString());
budget = (rd["budget"].ToString());
advance = (rd["advance"].ToString());
ddate = (rd["ddate"].ToString());
TextBox tobj = new TextBox();
tobj.Location = new Point(10, (40 + ((i - 2) * 20)));
tobj.Tag = 1;
tobj.Text = pname;
tobj.AutoSize = false;
tobj.Width = 150;
tobj.ReadOnly = true;
this.Controls.Add(tobj);
TextBox tobj1 = new TextBox();
tobj1.Location = new Point(160, (40 + ((i - 2) * 20)));
tobj1.Tag = 2;
tobj1.Text = cname;
tobj1.AutoSize = false;
tobj1.Width = 150;
tobj1.ReadOnly = true;
this.Controls.Add(tobj1);
TextBox tobj2 = new TextBox();
tobj2.Location = new Point(310, (40 + ((i - 2) * 20)));
tobj2.Tag = 3;
tobj2.Text = budget;
tobj2.AutoSize = false;
tobj2.Width = 100;
tobj2.ReadOnly = true;
this.Controls.Add(tobj2);
TextBox tobj3 = new TextBox();
tobj3.Location = new Point(410, (40 + ((i - 2) * 20)));
tobj3.Tag = 4;
tobj3.Text = advance;
tobj3.AutoSize = false;
tobj3.Width = 100;
tobj3.ReadOnly = true;
this.Controls.Add(tobj3);
TextBox tobj4 = new TextBox();
tobj4.Location = new Point(510, (40 + ((i - 2) * 20)));
tobj4.Tag = 5;
tobj4.Text = ddate;
tobj4.AutoSize = false;
tobj4.Width = 100;
tobj4.ReadOnly = true;
int due = 0;
due = int.Parse(ddate);
if (due < 5)
{
tobj4.BackColor = System.Drawing.Color.Red;
}
this.Controls.Add(tobj4);
Button button = new Button();
button.Left = 620;
button.Tag = i;
button.Height = 20;
button.Text = "Details";
button.Top = (40 + ((i - 2) * 20));
this.Controls.Add(button);
}
}
Please give me some ideas on how to generate the click event handler.
Answer part:
Add this:
button.Tag = i;
button.Click += handleTheClick;
...
private void handleTheClick(object sender, EventArgs e){
Button btn = sender as Button;
int row = (int)btn.Tag;
}
Un-answer:
You should reconsider your design. Including coordinates in your data processing code is a really bad idea in 2013, try using ListView, ListBox, GridView or better - switch to WPF.
You need to subscribe to the Click events:
button.Click += ... some event handler ...
You can use a method for the handler:
button.Click += MyEventHandlerMethod;
// put this method somewhere in your Form class
void MyEventHandlerMethod( object sender, EventArgs args )
{
...
Or even a lambda:
button.Click += ( s, e ) => HandleClick( ... any parameters here ... );
// put this method somewhere in your Form class
void HandleClick( ... required parameters ... )
{
...
As a hint, you can look in the .designer.cs file of a normal Form to see how things are done.

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