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
I have a button which I added programmatically and I want to store certain unique information with every button. I have saved the Name and Text but is there a way to store another string to access later. Below is the code for my button and it's click event.
for (int i = bankaccountsDatagridview.Rows.Count - 1; i >= 0; i--)
{
string buttonName = "individualDepartmentBtn-" + i;
FontAwesome.Sharp.IconButton individualDepartmentBtn = new FontAwesome.Sharp.IconButton();
individualDepartmentBtn.BackColor = System.Drawing.Color.White;
individualDepartmentBtn.Cursor = System.Windows.Forms.Cursors.Hand;
individualDepartmentBtn.Dock = System.Windows.Forms.DockStyle.Top;
individualDepartmentBtn.FlatAppearance.BorderSize = 0;
individualDepartmentBtn.FlatAppearance.MouseDownBackColor = System.Drawing.Color.Silver;
individualDepartmentBtn.FlatAppearance.MouseOverBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(224)))), ((int)(((byte)(224)))), ((int)(((byte)(224)))));
individualDepartmentBtn.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
individualDepartmentBtn.Flip = FontAwesome.Sharp.FlipOrientation.Normal;
individualDepartmentBtn.Font = new System.Drawing.Font("Roboto", 11.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
individualDepartmentBtn.ForeColor = System.Drawing.Color.DimGray;
individualDepartmentBtn.IconChar = FontAwesome.Sharp.IconChar.None;
individualDepartmentBtn.IconColor = System.Drawing.Color.DimGray;
individualDepartmentBtn.IconSize = 25;
individualDepartmentBtn.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft;
individualDepartmentBtn.Margin = new System.Windows.Forms.Padding(10);
individualDepartmentBtn.Padding = new System.Windows.Forms.Padding(30, 0, 0, 0);
individualDepartmentBtn.Name = bankaccountsDatagridview.Rows[i].Cells[1].Value.ToString();
individualDepartmentBtn.Rotation = 0D;
individualDepartmentBtn.Size = new System.Drawing.Size(192, 30);
individualDepartmentBtn.TabIndex = 1;
individualDepartmentBtn.Text = bankaccountsDatagridview.Rows[i].Cells[1].Value.ToString();
individualDepartmentBtn.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
individualDepartmentBtn.UseVisualStyleBackColor = false;
navigationPanel.Controls.Add(individualDepartmentBtn);
individualDepartmentBtn.MouseDown += new System.Windows.Forms.MouseEventHandler(individualBankBtnDown);
}
Click Event:
private void individualBankBtnDown(object sender, MouseEventArgs e)
{
bankTitle = ((FontAwesome.Sharp.IconButton)sender).Name.ToString();
}
You can use the Tag property. For example:
individualDepartmentBtn.Tag = "My String";
You can store any object within Tag and not only strings.
Note that you could also use the var keyword and an object initializer to make your code a little bit more readable:
var individualDepartmentBtn = new FontAwesome.Sharp.IconButton
{
BackColor = System.Drawing.Color.White,
Cursor = System.Windows.Forms.Cursors.Hand,
Dock = System.Windows.Forms.DockStyle.Top,
...
};
I'm attempting to display some dynamically generated labels next to dynamically generated text boxes. The text boxes appear but the labels do not.
I've looked at several solutions and have tried to make sure I defined all the label properties. I looked at some threading related solution that seem unnecessary because i'm not changing visibility state, I would just like to pop up the labels next to the text boxes.
TextBox[] channelNames = new TextBox[numOfChannels];
GroupBox channelBox = new GroupBox();
Label[] labelNames = new Label[numOfChannels];
for (int currentChannelIndex = 0; currentChannelIndex < numOfChannels; currentChannelIndex++)
{
var txt = new TextBox();
channelNames[currentChannelIndex] = txt;
txt.Name = channelCollection[currentChannelIndex].PhysicalName;
txt.Text = "ben";
txt.Location = new Point(200, 32 + (currentChannelIndex * 28));
txt.Visible = true;
this.channelBox.Controls.Add(channelNames[currentChannelIndex]);
var lbl = new Label();
labelNames[currentChannelIndex] = lbl;
lbl.AutoSize = true;
lbl.Name = channelCollection[currentChannelIndex].PhysicalName;
lbl.Size = new Size(55, 13);
lbl.TabIndex = 69;
lbl.Text = channelCollection[currentChannelIndex].PhysicalName;
lbl.Location = new Point(175, 32 + (currentChannelIndex * 28));
lbl.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.channelBox.Controls.Add(labelNames[currentChannelIndex]);
}
Here are a few things to check:
1) You are setting "AutoSize" and "Size". Trying removing "Size"
2) The default font is likely too large for the (55,13) size.
Try explicitly setting the font to something small to see if it shows up.
Does channelCollection[currentChannelIndex].PhysicalName actually contain a non-Empty string? e.g.:
class Something
{
public string PhysicalName { get; set; }
}
private void AddLabels()
{
Something[] channelCollection = new Something[]
{
//Applying this to Label.Text makes it "invisible"
new Something() { PhysicalName = "" }
};
var currentChannelIndex = 0;
var txt = new TextBox();
txt.Name = channelCollection[currentChannelIndex].PhysicalName;
txt.Text = "ben";
txt.Location = new Point(200, 32);
txt.Visible = true;
this.Controls.Add(txt);
var lbl = new Label();
lbl.AutoSize = true;
lbl.Name = channelCollection[currentChannelIndex].PhysicalName;
lbl.Size = new Size(55, 13);
lbl.TabIndex = 69;
lbl.Text = channelCollection[currentChannelIndex].PhysicalName;
lbl.Location = new Point(175, 32);
lbl.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.Controls.Add(lbl);
}
I actually had an exception that downstream of this code block that was causing the issue. I assumed that i would see the labels since the exception was thrown after the call to the label. Thanks for your suggestions.
Ok so I have this code to create controls on my form:
public CableID_DuplicateView(CableID_CreateView CView)
{
InitializeComponent();
Label lbl = new Label();
Button btn = new Button();
ComboBox cmb = new ComboBox();
TextBox txt = new TextBox();
if (CView.input == 1)
{
lbl.Text = "Please select a cable number to duplicate:";
lbl.Location = new Point(12, 9);
cmb.Location = new Point((lbl.Width + 17), 6);
cmb.Size = new System.Drawing.Size(125, 20);
btn.Location = new Point((lbl.Width + cmb.Width + 17), 5);
btn.Size = new System.Drawing.Size(90, 23);
btn.Text = "Add to Table";
this.Height = cmb.Height + 48;
this.Width = lbl.Width + cmb.Width + btn.Width + 34;
this.Controls.Add(lbl);
this.Controls.Add(cmb);
this.Controls.Add(btn);
}
}
Which produces this:
What is causing my label to get cut off like that? And why is the comboBox sitting in a strange location?
What is happening here is that label.width is 100 which is not covering the whole text do this instead:
lbl.Text = "Please select a cable number to duplicate:";
lbl.Location = new Point(12, 9);
lbl.Width = 200;
You can also do this:
lbl.AutoSize = true;
Try this to set AutoSize width Property:
lbl.Text = "Please select a cable number to duplicate:";
lbl.Location = new Point(12, 9);
lbl.AutoSize = true;
this.Controls.Add(lbl);
Width property will not be set until the control has been added to the parent container.
Problem : You didn't set Width for your Label Control.so it takes some default width for your Label
Solution: You need to set Width for your Label
Try This:
lbl.Size = new System.Drawing.Size(200, 20); //width = 200, height = 20
As others said the width for the label is too short.
Solution 1: Set the width to a larger fixed width:
lbl.Width = 200;
Solution 2: Set AutoSize to true:
lbl.AutoSize = true;
Solution 3: Combine a fixed width with the AutoEllipsis property:
lbl.Width = 100;
lbl.AutoEllipsis = true;
When using AutoEllipsis the label remains the set width,
but the shown text is followed by three dots to indicate that not all text is shown.
I have some trouble when i'm trying to click my dynamic controls in StackPanel.
I'm adding controls to Grid in this way...
void Opt()
{
TextBlock Title_1 = new TextBlock();
TextBlock Title_2 = new TextBlock();
CheckBox Kwota_exists = new CheckBox();
TextBox Title = new TextBox();
StackPanel Frame = new StackPanel();
Button OK = new Button();
Title_1.Text = "Dodaj kategorię";
Title_2.Text = "Aktywne kategorię";
Kwota_exists.Content = "Stała kwota?";
Title.Text = "Nazwa kategorii";
OK.Content = "Dodaj";
OK.IsEnabled = true;
OK.IsHitTestVisible = true;
OK.IsTabStop = true;
OK.ClickMode = ClickMode.Release;
Frame.IsHitTestVisible = true;
Kwota_exists.Checked +=Kwota_exists_Checked;
Title_1.FontSize = 50;
Title_2.FontSize = 50;
Title.FontSize = 20;
Frame.Height = 100;
Frame.Width = 400;
Title_1.Margin = new Thickness(0, 0, 0, 0);
Title_2.Margin = new Thickness(0, 220, 0, 0);
Frame.Margin = new Thickness(0, 70, 0, 0);
Frame.HorizontalAlignment = Windows.UI.Xaml.HorizontalAlignment.Left;
Frame.VerticalAlignment = Windows.UI.Xaml.VerticalAlignment.Top;
Frame.Orientation = Orientation.Horizontal;
Frame.Background = new SolidColorBrush(Windows.UI.Color.FromArgb(145, 56, 234, 21));
Frame.Children.Add(Kwota_exists);
Frame.Children.Add(Title);
Frame.Children.Add(OK);
GrdContent.Children.Add(Frame);
GrdContent.Children.Add(Title_1);
GrdContent.Children.Add(Title_2);
}
But when i'm trying to click button or check checkbox controls doesn't seem to response (unclickable).
Looks like i can't access them or i'm doing something wrong. I would be gradefull if someone explain me where i'm doing mistake.