C# change labels created in public class from form button click - c#

Having hard time understanding classes and why I can't access certain object.
How can i modify the code so I can change "map"(which is a bunch of labels) properties in all of my classes/events?
The method Draw2d() creates a couple of labels on the main form that I wish to change on different events(button click in this example).
Can someone help me, or just hint me into the right direction.
The Code:
public partial class Form1 : Form
{
public void Draw2d()
{
const int spacing = 20;
Label[][] map = new Label[5][];
for (int x = 0; x < 5; x++)
{
map[x] = new Label[5];
for (int y = 0; y < 5; y++)
{
map[x][y] = new Label();
map[x][y].AutoSize = true;
map[x][y].Location = new System.Drawing.Point(x * spacing, y * spacing);
map[x][y].Name = "map" + x.ToString() + "," + y.ToString();
map[x][y].Size = new System.Drawing.Size(spacing, spacing);
map[x][y].TabIndex = 0;
map[x][y].Text = "0";
}
this.Controls.AddRange(map[x]);
}
}
public Form1()
{
InitializeComponent();
}
public void Form1_Load(object sender, EventArgs e)
{
Draw2d();
}
private void button1_Click(object sender, EventArgs e)
{
map[0][0].Text = "1"; // <-- Doesn't work
}
}
Thanks!

you have to declare the map as property(global to class)
public partial class Form1 : Form {
public Label[][] map;
....
}
then you can use inside class like
this->map[...][...]
or from outside like
objClass->map[...][...]

My guess is that you added
public Label[][] map;
but forgot to change the second line of Draw2d from
Label[][] map = new Label[5][];
to
map = new Label[5][];
I just tried your code, and it works fine if you change those two lines. If that's not the problem, could you say what error you're getting, please?

Related

How to create MaterialSingleLineTextField Controls dynamically

I would like to add MaterialSingleLineTextField dynamically to a Form.
I have used MaterialSkin NuGet package:
I am trying to create multiple MaterialSkin TextBoxes dynamically on Form.Load. But no Controls are displaying in the hosing Panel.
private void Form1_Load(object sender, EventArgs e)
{
int n = 5;
int pointX = 30;
int pointY = 40;
//panel1.Controls.Clear();
for (int i = 0; i < n - 1; i++)
{
MaterialSingleLineTextField a = new MaterialSingleLineTextField();
a.Text = (i + 1).ToString();
a.Visible = true;
a.Location = new Point(pointX, pointY);
panel1.Controls.Add(a);
panel1.Show();
pointY += 20;
}
}
This code block works perfectly fine for normal TextBoxes.
Is there any way to add MaterialSingleLineTextField dynamically?
A sample Form initialization with default Theme values.
The MaterialSkinManager is initialized in the Form Constructor, setting the Theme to MaterialSkinManager.Themes.LIGHT and default color scheme. The Form base Type is set to MaterialForm.
A specified number of MaterialSingleLineTextField controls is added to a parent container (a Panel), starting from a defined Location downwards.
These Controls are anchored to the parent and the Height is set to Parent.Font.Height + 4.
It's important that you specify the Size of these Controls, otherwise you'll get a minimal size that prevents the Controls from showing their content.
As you can see in the AddTextFields() method, it's important that you dispose of the previous Controls added to the Parent container, if you want to replace the existing with new ones. Even more important using this Library.
Calling the Clear() method of a Control.Controls collection (as in the line you have commented out) doesn't dispose of anything, those controls are still alive.
public partial class Form1 : MaterialForm
{
private readonly MaterialSkinManager msManager = null;
public Form1()
{
InitializeComponent();
msManager = MaterialSkinManager.Instance;
msManager.AddFormToManage(this);
msManager.Theme = MaterialSkinManager.Themes.LIGHT;
}
private void Form1_Load(object sender, EventArgs e)
{
AddTextFields(panel1, 5, new Point(30, 10), false);
}
private void AddTextFields(Control parent, int controlsCount, Point startPosition, bool ClearExisting)
{
if (clearExisting && parent.Controls.Count > 0) {
for (int i = parent.Controls.Count - 1; i >= 0; i--) {
parent.Controls[i].Dispose();
}
}
int controlHeight = parent.Font.Height + 4;
int yIncrement = 0;
for (int i = 0; i < controlsCount; i++) {
var textField = new MaterialSingleLineTextField() {
Text = (i + 1).ToString(),
Size = new Size(parent.ClientSize.Width - startPosition.X - 4, controlHeight),
Location = new Point(startPosition.X, startPosition.Y + yIncrement),
Anchor = AnchorStyles.Left | AnchorStyles.Top | AnchorStyles.Right
};
parent.Controls.Add(textField);
yIncrement += (controlHeight + 10);
}
}
private void matBtnChangeTheme_Click(object sender, EventArgs e)
{
msManager.Theme = MaterialSkinManager.Themes.DARK;
msManager.ColorScheme = new ColorScheme(Primary.Blue600, Primary.Blue900, Primary.Blue500, Accent.LightBlue200, TextShade.WHITE);
}
private void matBtnAddControls_Click(object sender, EventArgs e)
{
AddTextFields(panel1, 7, new Point(30, 10), true);
}
}
Sample functionality:

How to display Form Components from List

this question might be really stupid but here it is anyway. What I want my programm to do: When I press a button I want to add a DatePicker Component to a List and then display all the Components in the Main Form. However when I press the button it only adds the components but doesnt show them in the Form Window. No Errors are thrown. What do I have to do to display the DatePicker Components in the Main Form?
//class containing the List of Components
class Eintrag
{
static public List<DateTimePicker> Anfangszeit = new List<DateTimePicker>();
}
//Main Form Class
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Eintrag.Anfangszeit.Add(new DateTimePicker());
for (int i = 0; i < Eintrag.Anfangszeit.Count; i++)
{
Eintrag.Anfangszeit[i].Location = new System.Drawing.Point(30, 50 + 50*i);
Eintrag.Anfangszeit[i].Size = new System.Drawing.Size(200, 20);
Eintrag.Anfangszeit[i].Visible = true;
Eintrag.Anfangszeit[i].Show();
}
}
}
John Wu is right, you have to add the Controls to the Form via Controls.Add()
private void button1_Click(object sender, EventArgs e)
{
Eintrag.Anfangszeit.Add(new DateTimePicker());
for (int i = 0; i < Eintrag.Anfangszeit.Count; i++) {
Eintrag.Anfangszeit[i].Location = new System.Drawing.Point(30, 50 + 50 * i);
Eintrag.Anfangszeit[i].Size = new System.Drawing.Size(200, 20);
Eintrag.Anfangszeit[i].Visible = true;
this.Controls.Add(Eintrag.Anfangszeit[i]);
Eintrag.Anfangszeit[i].Show();
}
}

Data from dynamically added parsed textboxes

I'm making a simple calculator to save myself from having to add up a bunch of invoice totals on basic calculator at work (since we use paper invoices). I'm just getting the basic functionalities in place currently and one of the functions I have is adding extra textboxes and then later trying to add all of the values in the textboxes to a subtotal. The problem I am having (I think) is that the compiler needs to have the the textbox ID's before the program is compiled. I'm also going to apologize for the sloppy variable names, I tried everything I could think of in my basic mindset until 4AM and by the time I was just using any variable. I've tried all the iterations, (ended up with do while statement as you can see).
namespace WindowsFormsApp1
{
public partial class Form1 : Form
{
int partboxes = 3;
int lastY = 83;
public Form1()
{
InitializeComponent();
}
private void buttonFinal_Click(object sender, EventArgs e)
{
AddParts();
}
public double AddParts()
{
int i = 1;
double megavalue = 0;
do
{
double totalsum = double.Parse(("partBox" + i).Text);
megavalue = totalsum + megavalue;
i = i + 1;
} while (i < partboxes);
string supervalue = megavalue.ToString();
lblPartsTotal.Text = supervalue;
return megavalue;
}
private void button1_Click(object sender, EventArgs e)
{
TextBox partBox = new TextBox();
partBox.Name = "partBox" + partboxes++;
partBox.Location = new System.Drawing.Point(12, lastY + 26);
partBox.Size = new System.Drawing.Size(100, 20);
// Add the textbox control to the form's control collection
this.Controls.Add(partBox);
lastY = lastY + 26;
partboxes = partboxes++;
}
}
}
You can get a textbox by name from the Controls property with
var tb = (TextBox)Controls["partBox" + i];
where i is the textbox number.
The indexer returns a Control. But since every control has a Text property, you can use it without casting.
double totalsum = double.Parse(Controls["partBox" + i].Text);
See: Control.ControlCollection Class

Using Dynamic Textboxes in C# Program

I am trying to make number of TextBoxes according to number in TextBox1 and I want to use each TextBox value in my program. Their name becames txtbx0, txtbx1... but when I want to use in my program, it gives error "The name 'txtbx1' does not exist in the current context". How can I use them in my program?
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
int y = Convert.ToInt32(textBox1.Text);
TextBox[] txtbx = new TextBox[y];
for (int i = 0; i < y; i++)
{
txtbx[i]= new TextBox();
txtbx[i].Location = new Point(20, i * 50);
txtbx[i].Size = new Size(100,50);
txtbx[i].Name = "txtbx"+i.ToString();
txtbx[i].Text = txtbx[i].Name;
flowLayoutPanel1.Controls.Add(txtbx[i]);
}
}
The way you have it right now, the textboxes could be accessed by using your array txtbx[whateverNumber]. In order to make them accessible outside of the method you posted, you'll need to make your txtbx array a class member instead of a method-scoped variable.
Something like:
class Form1 : Form
{
TextBox[] txtbx;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
int y = Convert.ToInt32(textBox1.Text);
txtbx = new TextBox[y]; // Now this references the class member
for (int i = 0; i < y; i++)
... etc.
}
}
Accessing them individually by name is not really feasible because you'd have to have class member variables for each of them, but you don't know up front how many to make. The array method like you're doing is much better. You can just access them in other methods using txtbx[0] through txtbx[numBoxes - 1].

Increment number per button click C# Desktop

I'm trying to create a mathematical game with a timer that calculates the number of correct questions within a specific time. Now I'm trying to increment an int value per button click if the answer is correct.
But it only increment once and sometimes does not increment:
private void button1_Click(object sender, EventArgs e)
{
int x = Randomnumber.Next(12);
int z = Randomnumber.Next(12);
int s = x * z;
int correct = 0;
//int cv = +correct;
textBox2.Text = x.ToString();
textBox3.Text = z.ToString();
if (s == Convert.ToInt32(textBox4.Text))
{
correct += 1;
numbercorrect.Text = correct.ToString();
}
}
your main form(i'm assuming you're using forms) is a class.
What I'd suggest is declaring a variable as a member of your forms class, and using that to hold the number of correct responses.
I'd imagine something like the following;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
int correct;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
//insert logic here
correct++;
}
}
}
You need to move int correct declaration to class scope. Otherwise with every click, you start with new variable.
int correct = 0; is scoped within the function. Move it outside the function as a class field. That way it will preserve its value instead of being reset to 0 during each click.
Try this:
private int correct = 0;
private void button1_Click(object sender, EventArgs e)
{
int x = Randomnumber.Next(12);
int z = Randomnumber.Next(12);
int s = x * z;
//int cv = +correct;
textBox2.Text = x.ToString();
textBox3.Text = z.ToString();
if (s == Convert.ToInt32(textBox4.Text))
{
correct ++;
numbercorrect.Text = correct.ToString();
}
You always start your count with 0, and never get the original value.
Now the variable holding the data is outside the function and initialized when the form loads.
Every time the button is clicked, correct is beging reset to zero.
Try declaring correct outside of the method.
Try look at code bellow:
int correct = 0;
tryParse(numbercorrect.Text, out correct);
So your code must be like:
private void button1_Click(object sender, EventArgs e)
{
int x = Randomnumber.Next(12);
int z = Randomnumber.Next(12);
int s = x * z;
int correct = 0;
int.tryParse(numbercorrect.Text, out correct);
//int cv = +correct;
textBox2.Text = x.ToString();
textBox3.Text = z.ToString();
if (s == Convert.ToInt32(textBox4.Text))
{
correct += 1;
numbercorrect.Text = correct.ToString();
}

Categories

Resources