Can't access buttons from Form_Load in event handler - c#

I have three buttons in Form_Load, to every button I give size, location and text.
When I click one of the buttons a new button appears, which should take me to the first screen with the three original buttons. I clear the screen and add the buttons, but I get an error "the name 'button' does not exist in the current context". What can I do to have access to these buttons. Thanks.
Form_Load:
Button play = new Button();
Button howtoplay = new Button();
Button puzzles = new Button();
play.Size = new Size(175, 70);
puzzles.Size = new Size(175, 70);
howtoplay.Size = new Size(175, 70);
play.Location = new Point((ClientRectangle.Right/2)-(play.Width/2), 135);
puzzles.Location = new Point((ClientRectangle.Right / 2) - (play.Width / 2), 210);
howtoplay.Location = new Point((ClientRectangle.Right / 2) - (play.Width / 2), 285);
play.Text = "Play";
howtoplay.Text = "How To Play";
puzzles.Text = "Puzzles";
Controls.Add(play);
Controls.Add(howtoplay);
Controls.Add(puzzles);
howtoplay.Click += new EventHandler(howtoplay_click);
howtoplay_click:
play.Hide();
puzzles.Hide();
howtoplay.Hide();
Button backB = new Button();
backB.Size = new Size(100, 50);
backB.Location = new Point((ClientRectangle.Right - backB.Width - 10), (ClientRectangle.Bottom - backB.Height - 10));
backB.Text = "Back";
backB.Click += new EventHandler(Back_Click);
Controls.Add(backB);
Back_Click:
Controls.Clear();
Controls.Add(play); //error
Controls.Add(puzzles); //error
Controls.Add(howtoplay); //error

You have declared buttons as local variables of Form_Load event handler method:
private void Form_Load(object sender, EventArgs e)
{
Button play = new Button();
Button howtoplay = new Button();
Button puzzles = new Button();
// ...
}
These variables are not available outside the method. You should use form fields instead:
// available in all instance methods of form
Button play;
Button howtoplay;
Button puzzles;
private void Form_Load(object sender, EventArgs e)
{
play = new Button();
howtoplay = new Button();
puzzles = new Button();
// ...
}
Note: Usually you should manually create controls only when those controls should be added to your form dynamically at runtime. But you are creating controls in Form_Load event handler, so I suggest you use designer to create controls. It will create a class field for each control and add appropriate initialization code. All you need to do is drag-and-drop control (buttons in this case) from toolbox to form and setup each control properties.

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

how to create a button that creates another button and show up immediately

I want to create a button that Creates other buttons and I want it to be able to create like infinite buttons on the screen
I tried
Button button = new Button();
button.Location = new Point(100,100);
button.Text = "IT Woreked";
button.Size = new Size(26,26);
button.Visible = true;
Application.Restart();
this.Controls.Add(button);
and I believe it really adds it but it's not shown up
so how do I add the button to the screen
I think that is because you are putting all the new buttons in the same location. Also, remove the Application.Restart() part.
Button button = new Button();
button.Location = new Point(100,100); //change this to random or something
button.Text = "IT Woreked";
button.Size = new Size(26,26);
button.Visible = true;
Application.Restart();//don't restart the application everytime you click!
this.Controls.Add(button);
You should also subscribe to the new buttons' OnClick event. You should create a local function that contains all the above code and subscribe to the new buttons. This way you can add buttons recursively. Say if the original button's name is button1, change its click method to something like this:
private void button1_Click(object sender, EventArgs e)
{
Random random = new Random(System.Environment.TickCount);//random location everytime
Button button = new Button();
button.Text = "IT Woreked";
button.Size = new Size(26, 26);// the size might be a bit small. You might want to increase it.
button.Location = new Point(random.Next(0, this.Size.Width - button.Width), random.Next(0, this.Size.Height - button.Height)); //change this to random or something
button.Visible = true;
this.Controls.Add(button);
button.Click += button1_Click;//when the new button is clicked, call this method.
}

How to create multiple RichTextBoxes

I need to crate a certain number of RichTextBoxes depending on User Input.
I can create one in visual studio using the toolbox, but how would I go about creating multiple through code?
UPDATE:
This is now my code:
RichTextBox richTextBox = new RichTextBox();
richTextBox.Location = new Point(12, 169);
richTextBox.Width = 62;
richTextBox.Height = 76;
this.Controls.Add(richTextBox);
Nothing happens when I run this
OK. Here is a sample that shows that it works:
void Main()
{
Form f = new Form();
Button b = new Button();
b.Click += (sender, args) =>
{
RichTextBox richTextBox = new RichTextBox
{
Name = "rtbBlahBlah",
Location = new System.Drawing.Point(12, 169),
Width = 62,
Height = 76
};
f.Controls.Add(richTextBox);
};
f.Controls.Add(b);
f.Show();
}
Call this.Refresh() to refresh the Control and re-draw all the children within it.
From the Docs:
Forces the control to invalidate its client area and immediately redraw itself and any child controls.

Dynamic button and create textbox

I have a textbox and button on c# form and users can enter number.I create a label which users want and each label have a button.Here if I click those buttons i wanna create textbox but if users continue to click,i want to create more textbox.
Button[] Btn= new Button[10];
for (int i = 0; i < labelNumber; i++)
{
Btn[i] = new Button();
Btn[i].Text = "Add";
Btn[i].Location = new Point(40, 100 + i * 29);
Btn[i].Size = new Size(50,20);
this.Controls.Add(Btn[i]);
Btn[i].Click += new EventHandler(addNewTextbox);
}
on the code above; for example; if labelNumber == 3 so i have 3 label and 3 button with them, if i click add button i wanna create textbox near thislabel.
private void addNewTextbox(object sender, EventArgs e)
{
TextBox[] dynamicTextbox = new TextBox[10];
Button dinamikButon = (sender as Button);
int yLocation = (dinamikButon.Location.Y - 100) / 29;
//int xLocation = dinamikButon.Location.X - 100;
dynamicTextbox[yLocation] = new TextBox();
dynamicTextbox[yLocation].Location = new Point(100, 100 + yLocation * 29);
dynamicTextbox[yLocation].Size = new Size(40, 50);
this.Controls.Add(dynamicTextbox[yLocation]);
}
here i change textbox y coordinates but i couldn't it for X. if i change this
dynamicTextbox[yLocation].Location = new Point(100*x, 100 + yLocation * 29);
x++;
it sort equals all of them.
Label1 Button1
Label2 Button2
Label3 Button3
if i click Button1 4 times,it has to create 4 textbox alongside label1. and if i click Button2 2 times,it has to create 2 textbox alongside label2
Please Help ME.
The simplest way is to keep a list containing the created textboxes in the button's Tag property like this
private void addNewTextbox(object sender, EventArgs e)
{
var button = (Button)sender;
var textBoxes = button.Tag as List<TextBox>;
if (textBoxes == null)
button.Tag = textBoxes = new List<TextBox>();
var textBox = new TextBox();
textBoxes.Add(textBox);
textBox.Location = new Point(100 * textBoxes.Count, button.Top);
textbox.Size = new Size(40, 50);
this.Controls.Add(textBox);
}
This way you not only can add a new text box, but also can easily determine the created text boxes by each button at any time if needed.

How to check if a space on the form has an object

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);

Categories

Resources