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
So I need to add textboxes to a panel with a click of a button. Every click adds one textbox under the last one and so on. But when it goes over the panel height it suddenly makes bigger space between the texboxes even though the int is still the same.
Here's my code so far.
List<TextBox> textboxes = new List<TextBox>();
private void button1_Click(object sender, EventArgs e)
{
tbY += 30;
TextBox tb = new TextBox();
tb.Left = 3;
tb.Top = tbY;
tb.Font = new Font("Verdana", 12, FontStyle.Bold);
tb.Size = new Size(325, 25);
tb.BorderStyle = BorderStyle.None;
button1.Top = tbY;
panel1.Controls.Add(tb);
textboxes.Add(tb);
ScrollToBottom(panel1);
}
The Top of a Control is calculated relative to the scroll position of its Parent.
You are always scrolling to the bottom of your Panel, so you need to set it like this, taking the curent scroll position into account:
tb.Top = tbY + panel1.AutoScrollPosition.Y;
Note that the AutoScrollPosition.Y is negative when you have scrolled downward, so we need to add it!
You might as well use a flowLayoutPanel for this purpose. Use the following properties on your flowLayoutPanel and it'll work as you intend. (without having to do the manual calculation)
List<TextBox> textboxes = new List<TextBox>();
public Form1()
{
InitializeComponent();
flowLayoutPanel1.FlowDirection = FlowDirection.TopDown;
flowLayoutPanel1.WrapContents = false;
flowLayoutPanel1.AutoScroll = true;
}
private void button1_Click(object sender, EventArgs e)
{
TextBox tb = new TextBox();
tb.Left = 3;
tb.Font = new Font("Verdana", 12, FontStyle.Bold);
tb.Size = new Size(325, 25);
tb.Text = tb.Top.ToString();
tb.BorderStyle = BorderStyle.None;
flowLayoutPanel1.Controls.Add(tb);
textboxes.Add(tb);
}
I'm working on a mind-map project. I'm trying to get the "New Bubble" button to create a new textbox into a FREE space on the form. So I want to check if there is another bubble in the place where it's getting created. If it already has a textbox then I want it to find a new place and repeat the process.
How can I do this?
public partial class frmMap : Form
{
private void btnProperties_Click(object sender, EventArgs e)
{
new frmProperties().Show();
}
private void btnNewBubble_Click(object sender, EventArgs e)
{
var tb = new TextBox();
tb.Multiline = true;
tb.BorderStyle = BorderStyle.FixedSingle;
tb.Top = 100;
tb.Left = 200;
tb.Size = new Size(100, 100);
this.Controls.Add(tb);
}
}
You can check "collision" with other controls like so:
foreach (Control checkControl in Controls)
{
if (tb.Bounds.IntersectsWith(checkControl.Bounds))
...
}
Of course, thats a lot of checking to do! If you are just going to "grid" the controls, it would be faster/easier to just layout a bool array that holds the state of each "cell" (filled/empty) then pick the first empty one you find.
Create dynamic textbox:
var tb = new TextBox();
tb.Multiline = true;
tb.BorderStyle = BorderStyle.FixedSingle;
tb.Top = 100;
tb.Left = 200;
tb.Size = new Size(100, 100);
Then use Rectangle.IntersectWith to check if new textbox intersects with other already added texboxes (you can remove control type filter, if you have other type of controls to check):
while(Controls.OfType<TextBox>().Any(x => tb.Bounds.IntersectsWith(x.Bounds))
{
// adjust tb size or position here
}
And last step - add textbox to form:
Controls.Add(tb);
How can I get PropertyGrid's TextBox from specified field?
I need this TextBox to set Pointer to the end of text.
var num = txtBox.GetCharIndexFromPosition(Cursor.Position);
txtBox.SelectionStart = num + 1;
txtBox.SelectionLength = 0;
So how can I get this TextBox from PropertyGrid?
Also, property in PropertyGrid is read-only.
If what you want is the cursor to be located right after the last character written in the textbox, you can rely on the following code (triggered by the TextChanged Event of the TextBox):
private void txtBox_TextChanged(object sender, EventArgs e)
{
int newX = txtBox.Location.X + TextRenderer.MeasureText(txtBox.Text, txtBox.Font).Width;
int newY = txtBox.Bottom - txtBox.Height / 2;
if (newX > txtBox.Location.X + txtBox.Width)
{
newX = txtBox.Location.X + txtBox.Width;
}
Cursor.Position = this.PointToScreen(new Point(newX, newY));
}
Bear in mind that its Y position is always in the middle.
----- UPDATE AFTER THE KINGKING COMMENT
As far as the code in the question was referred to the TextBox, I focused my answer on the TextBox. Nonetheless, KingKing is right and the PropertyGrid has to be brought into consideration. Below these lines I adapted the code you can find in MSDN for PropertyGrid:
private void Form1_Load(object sender, EventArgs e)
{
PropertyGrid propertyGrid1 = new PropertyGrid();
propertyGrid1.CommandsVisibleIfAvailable = true;
propertyGrid1.Location = new Point(10, 20);
propertyGrid1.Size = new System.Drawing.Size(400, 300);
propertyGrid1.TabIndex = 1;
propertyGrid1.Text = "Property Grid";
this.Controls.Add(propertyGrid1);
propertyGrid1.SelectedObject = txtBox;
}
After txtBox is added to propertyGrid1, its position is updated and thus the original code can be used without any problem.
In summary, the idea is not looking for the TextBox inside the PropertyGrid, but accessing directly the TextBox control (which is added at runtime to the PropertyGrid).
I have a form which is an MDI container. In that form i generate 6 child forms each with a label:
for (int i = 0; i < 6; i++)
{
Form window = new Form();
window.Width = 100;
window.Height = 100;
window.MdiParent = this;
window.FormBorderStyle = FormBorderStyle.FixedToolWindow;
Label label = new Label();
label.AutoSize = true;
label.Location = new System.Drawing.Point(1, 1);
label.Size = new System.Drawing.Size(35, 13);
label.TabIndex = 1;
label.Name = "label" + i.ToString();
label.Text = window.Top.ToString();
window.LocationChanged += new System.EventHandler(HERE);
window.Controls.Add(label);
window.Show();
}
I added an event on the locationchanged for window. Now how do do it so that label updates to the windows position?
I think this line will do the trick for you:
window.LocationChanged += new EventHandler(delegate(object o, EventArgs evtArgs) {
label.Text = window.Location.ToString();
});
Well, it's easiest to do it with a lambda expression or an anonymous method:
window.LocationChanged += (sender, args) => label.Text = window.Top.ToString();
If you're using C# 1.1 you'd need to be a bit trickier because of the label being captured automatically in C# 2+ - you'd have to create a new class like this:
internal class LocationChangeNotifier
{
private readonly Label label;
internal LocationChangeNotifier(Label label)
{
this.label = label;
}
internal void HandleLocationUpdate(object sender, EventArgs e)
{
label.Text = ((Control) sender).Top.ToString();
}
}
then use it as:
LocationChangeNotifier notifier = new LocationChangeNotifier(label);
window.LocationChanged += new EventHandler(notifier.HandleLocationUpdate);
Aren't captured variables great? :)