How to create labels for each element? - c#

I have the following code. On form load, I want to create multiples labels, the first should be on position (20,0), the second on the (40,0) and till the last label. But the program just shows the first label, I mean label 0, and that's all.
How to fix this?
private void Form1_Load(object sender, EventArgs e)
{
Label[] nmr = new Label[10];
for(int i=0; i<10; i++)
{
nmr[i] = new Label();
nmr[i].Text = "label " + i;
nmr[i].Left += 20;
this.Controls.Add(nmr[i]);
}
}

nmr[i].Left = 20 * (i+1);
will calculate the distance you want. Yet, you will only see one label because the first label is too long. So you have to adjust its size:
nmr[i].Size = new Size(40, 15);
Then you will see that 20 pixels is way too small as a distance; the labels will overlap

private void Form3_Load(object sender, EventArgs e)
{
Label[] nmr = new Label[10];
for (int i = 0; i < 10; i++)
{
nmr[i] = new Label();
nmr[i].Text = "label " + i;
nmr[i].Location = new Point(0, 25 * i);
this.Controls.Add(nmr[i]);
}
this.Height = this.Height + (25 * nmr.Count());
}
you also need to resize your form as well,
this code will help you,

In your loop, replace
nmr[i].Left +=20;
with
nmr[i].Left = 20 * (i + 1);

You should increase the Left value by 20 for each iteration. I also don't see why you are populating an array since you just add the Labels to the Controls collection. Try this:
private void Form1_Load(object sender, EventArgs e)
{
for (int i = 1; i < 11; i++)
{
var label = new Label();
label.Text = "label " + i;
label.Left += 20 * i;
this.Controls.Add(label);
}
}

Actually, you don't edit the right property. The right one would be control.Location which is a Point with the properties x and y.
To add them with 20 for every loop, you actually need to go like (20 * (i+1))
Example code that worked:
private void Form1_Load(object sender, EventArgs e)
{
Label[] nmr = new Label[10];
for (int i = 0; i < 10; i++)
{
nmr[i] = new Label();
nmr[i].Text = "label " + i;
nmr[i].Location = new Point(0, (20 * (i+1)));
this.Controls.Add(nmr[i]);
}
}
EDIT: Work on that 20 pt. Seems like the labels won't show right. Maybe try 30pt?

Try using Linq in order do generate Labels:
using System.Linq;
...
private void Form1_Load(object sender, EventArgs e) {
Label[] nmr = Enumerable
.Range(0, 10)
.Select(i => new Label() {
Text = $"label {i}",
Left = 20 + i * 20, // <- please, notice Left computation
Parent = this, })
.ToArray();
}

Related

Randomly put an image in specific places using C#

I am absolutely new with C#, so I hope my question is not completely off.
As you can see in the picture above, I have a form, in which there is a table (image) and a button. In the resources of the project, I have another image (black_rectangle.png), which is a black rectangle, exactly at the same size of each the table's cell. This is what I'm trying to achieve:
Each time the 'Again' button is clicked, I want the six black rectangles to cover two of the tree cells in each column, in a random manner. For example, after the first try, the table could look like this:
I'm basically stuck at the beginning:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Random rand = new Random();
List<PictureBox> items = new List<PictureBox>();
PictureBox newPic= new PictureBox();
newPic.Height = 50;
newPic.Width = 50;
newPic.BackColor = Color.Maroon;
int x = rand.Next(10, this.ClientSize.Width - newPic.Width);
int y = rand.Next(10, this.ClientSize.Height - newPic.Height);
newPic.Location = new Point(x, y);
}
}
Assuming the table (image) is in "pictureBox1", you could try something like:
private Random rnd = new Random();
private List<int> positions = new List<int> { 0, 1, 2 };
private List<PictureBox> prevBoxes = new List<PictureBox>();
private void button1_Click(object sender, EventArgs e)
{
prevBoxes.ForEach(pb => pb.Dispose()); // remove previous boxes
for(int col=0; col<3; col++)
{
positions = positions.OrderBy(i => rnd.Next()).ToList(); // shuffle positions
for(int i=0; i<2; i++)
{
PictureBox newPic = new PictureBox();
newPic.Height = 50;
newPic.Width = 50;
newPic.BackColor = Color.Maroon;
newPic.Location = new Point(pictureBox1.Left + (col * 50), pictureBox1.Top + (positions[i] * 50));
this.Controls.Add(newPic);
newPic.BringToFront();
prevBoxes.Add(newPic);
}
}
}
Output:

Combobox values depending on other combobox values

Using visual c# I have 5 combobox's. I want all to have numbers 1-5, but when one is selected, all others disappear. I.e. if I select number 3 from combobox 1, none of the others have the number 3. Any ideas? I would post code but pretty stuck for ideas in this. Thanks in advance
You can add the ComboBox programmatically on your Parent ComboBox like:
private void ComboBoxParent_SelectedIndexChanged(object sender, EventArgs e)
{
int numComboBoxes = 5;
for (int i = 0; i < numComboBoxes; i++)
{
ComboBox comboBoxChild = new System.Windows.Forms.ComboBox();
comboBoxChild.Location = new System.Drawing.Point(0, 21 * i);//Position on the Form
comboBoxChild.Size = new System.Drawing.Size(121, 21);//Size of the ComboBox
this.Controls.Add(comboBoxChild);
}
}
private void ComboBoxParent_SelectedIndexChanged(object sender, EventArgs e)
{
int numComboBoxes = 5;
ComboBox SelectedCombo = sender as ComboBox;
for (int i = 0; i < numComboBoxes; i++)
{
ComboBox comboBoxChild = new System.Windows.Forms.ComboBox();
comboBoxChild.Location = new System.Drawing.Point(0, 21 * i);
comboBoxChild.Size = new System.Drawing.Size(121, 21);
this.Controls.Add(comboBoxChild);
comboBoxChild.SelectedIndex=SelectedCombo.SelectedIndex;
}
}

Auto arrange unlimited number of buttons on form

I'm trying generate dynamically a bunch of buttons. The number of buttons is determined by how many pits are alive, and this is retrieved from a database.
Here is how it looks like :
Here is what I used to generate them :
private void Form1_Load(object sender, EventArgs e)
{
int numOf = pits.numOfPits();
Button[] genButtons = new Button[numOf];
int l = 1;
for (int i = 0; i < numOf; i++)
{
genButtons[i] = new Button();
genButtons[i].Width = 160;
genButtons[i].Height = 80;
Point location = new Point((i + 1) *200,75);
if (location.X > this.ClientSize.Width - 200)
{
location.X = l * 200;
location.Y += 100;
l++;
}
genButtons[i].Location = location;
this.Controls.Add(genButtons[i]);
}
}
The problem is that it will only work for 2 rows and it is kind of hard coded. How can I improve it to support an unlimited number of buttons.
You can ignore the limited "height" of form for the purpose of this question. I'll probably add some pagination later.
Add button controls to the FlowLayoutPanel. Extend the FlowLayoutPanel to include items per page, current page, and data to implement paging.
private void Form1_Load(object sender, EventArgs e)
{
FlowLayoutPanel flp = new FlowLayoutPanel();
for (int i = 0; i < pits.numOfPits(); ++i)
{
Button btn = new Button();
btn.Width = 160;
btn..Height = 80; //set padding or margin to appropriate values
flp.Controls.Add(btn);
}
this.Controls.Add(flp);
}

Printing Multiple Pages in a Winform application

I am attempting to print something using a C# Winforms application. I can't seem to understand how multiple pages works. Let's say I have the following code in my constructor:
private string _stringToPrint;
_stringToPrint = "";
for (int i = 0; i < 120; i++)
{
_stringToPrint = _stringToPrint + "Line " + i.ToString() + Environment.NewLine;
}
Then I have this code on my button click event:
private void MnuFilePrintClick(object sender, EventArgs e)
{
var pd = new PrintDocument();
pd.PrintPage += pd_PrintPage;
var z = new PrintPreviewDialog { Document = pd };
z.ShowDialog(this);
}
void pd_PrintPage(object sender, PrintPageEventArgs e)
{
Graphics g = e.Graphics;
var font = new Font("Arial", 10f, FontStyle.Regular);
g.DrawString(_stringToPrint, font, Brushes.Black, new PointF(10f, 10f));
}
Right now, when I run this code, it is giving me one page and after like 70 lines, it just runs off the paper. How would I print this string so that it prints enough for one page, then runs over to the second page, etc..?
You could have a counter and set the amount of lines you want per page like so:
private string[] _stringToPrint = new string[100]; // 100 is the amount of lines
private int counter = 0;
private int amtleft = _stringToPrint.Length;
private int amtperpage = 40; // The amount of lines per page
for (int i = 0; i < 120; i++)
{
_stringToPrint[i] ="Line " + i.ToString();
}
Then in pd_PrintPage:
void pd_PrintPage(object sender, PrintPageEventArgs e)
{
int currentamt = (amtleft > 40)?40:amtleft;
Graphics g = e.Graphics;
var font = new Font("Arial", 10f, FontStyle.Regular);
for(int x = counter; x < (currentamt+counter); x++)
{
g.DrawString(_stringToPrint[x], font, Brushes.Black, new PointF(10f, (float)x*10));
// x*10 is just so the lines are printed downwards and not on top of each other
// For example Line 2 would be printed below Line 1 etc
}
counter+=currentamt;
amtleft-=currentamt;
if(amtleft<0)
e.HasMorePages = true;
else
e.HasMorePages = false;
// If e.HasMorePages is set to true and the 'PrintPage' has finished, it will print another page, else it wont
}
I have had bad experiences with e.HasMorePages so this may not work.
Let me know if this works and I hope it helps!

Retrieving the mouse position

i have the following code and am trying to retrieve the cursor/mouse position when it is over the drawn array and output it to the lab:
Label[ , ] _arr = new Label[4 , 4];
private void Form1_Load(object sender, EventArgs e)
{
for(int i=0;i<4;i++)
{
for(int j=0;j<4;j++)
{
_arr[i ,j] = new Label();
_arr[i ,j].Text = ""+i+","+j;
_arr[i ,j].Size = new Size(50,50);
_arr[i ,j].Location = new Point(j*50,i*50); //you can set other property here like Border or else
_arr[i, j].BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle ;
this.Controls.Add(_arr[i ,j]);
**label2.Text = _arr[i, j].(System.Windows.Forms.Control.MousePosition).ToString();**
}
}
}
but i am having trouble with the line within double asterisks, can anyone help me resolve this error?
You could try something like this. It might not be the best way to do it, but it gives the desired result of updating the label as the mouse moves between each cell in your "array" on the form:
private void Form1_Load(object sender, EventArgs e)
{
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 4; j++)
{
_arr[i, j] = new Label();
_arr[i, j].Text = "" + i + "," + j;
_arr[i, j].Size = new Size(50, 50);
_arr[i, j].Location = new Point(j * 50, i * 50); //you can set other property here like Border or else
_arr[i, j].BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.Controls.Add(_arr[i, j]);
_arr[i, j].MouseMove += new MouseEventHandler(Form1_MouseMove);
}
}
}
void Form1_MouseMove(object sender, MouseEventArgs e)
{
label1.Text = ((Label)sender).Text;
}

Categories

Resources