I am creating some labels and text boxes when a combo box changes. I am using a tableFlowContainer with 2 columns and 5 rows. This works fine the first time the selection is changed but if I make another selection the labels and textboxes are not honoring the assigned location but seem to be inserting at 1 element increments. what should be {0,0} is {0,1} and {0,1} goes to {1,0} and so on.
Is there a way of clearing any labels and text boxes before rewritting the?
Here is my code.
private void cbPI_SelectedIndexChanged(object sender, EventArgs e)
{
//TextBox[] txtBox = new TextBox[5];
// Label[] lbls = new Label[5];
for (int x = 0; x <= 4; x++)
{
txtBoxs[x] = new TextBox();
this.txtBoxs[x].Text = "Text"+x;
this.txtBoxs[x].Name = "txtBoxName"+x;
this.txtBoxs[x].Anchor = System.Windows.Forms.AnchorStyles.Top;
this.Controls.Add(txtBoxs[x]);
lbls[x] = new Label();
this.lbls[x].Text = "label"+x;
this.lbls[x].Name = "lblBoxName1"+x;
this.lbls[x].Anchor = System.Windows.Forms.AnchorStyles.Right;
this.Controls.Add(lbls[x]);
tableLayoutPanel1.Controls.Add((lbls[x]), 0, x);
tableLayoutPanel1.Controls.Add(txtBoxs[(x)], 1, x);
}
}
By breaking at the controls the x variable is correct put the placement in the display is not.
Related
Say if I want to create a multiple button on my form based on a loop value of 3 then 3 buttons should be created into that form, in my case I have this textbox input that should determine the loop value on button click. What I've tried:
void Button4Click(object sender, EventArgs e)
{
int get_col_range = Convert.ToInt32(textBox3.Text);
for(int i=0; i<get_col_range; i++) {
Button btn = new Button();
btn.Text = Convert.ToString(i);
this.Controls.Add(btn);
}
}
I put on value of 2 on the TextBox input as test value but turned out that nothing happened why?.
Try the following on a form with no controls in a button click event.
int top = 10;
int heightPadding = 30;
for (int index = 0; index < 3; index++)
{
var button = new Button()
{
Text = $"Button {index}",
Name = $"Button{index}",
Location = new Point(10, top)
};
Controls.Add(button);
top += heightPadding;
}
I want to be able to do something like this so that i can just add label then label1 label 2 label3 etc and i cant create an array of new labels or anything since my labels have an image attached to them and have to keep a certain position as well. So making a new label that has some text as a label that wont show up anywhere in particular on my form isn't much use.
List<Label> labels = new List<Label>();
for (int i = 0; i < 10; i++)
{
labels.Add(label + (i.ToString()));
}
You can add Labels to list from Form by name like this :
List<Label> labels = new List<Label>();
for (int i = 0; i < 10; i++)
{
var label =
this.Controls.OfType<Label>().Where(lb => lb.Name == "label" + i).FirstOrDefault();
if (label != null)
labels.Add(label);
}
Here is a Code Sample:
You need to add the labels to the Controls collection of the tab page:
Page2.Controls.Add(CustomLabel[CustomLabel.Count - 1] as Control);
List<Label> customLabels = new List<Label>();
foreach (string ValutaCustomScelta in Properties.Settings.Default.ValuteCustom)
{
Label label = new Label();
label.Location = new System.Drawing.Point(317, 119 + customLabels.Count*26);
label.Parent = Page2;
label.Name = "label" + ValutaCustomScelta;
label.Text = ValutaCustomScelta;
label.Size = new System.Drawing.Size(77, 21);
customLabels.Add(label);
Page2.Controls.Add(label);
}
Have you added the labels by code or by design?
If you added them by code just add them then to the list.
If you added them by design there are two options. They are all on the same container (panel, form, groupbox...) or they are not.
If they are you can:
for each(control ctr in $yourcontainer.controls)
{
if(ctr is Label)
{
labels.add(ctr);
}
}
If they are not in the same container you can add them by hardcode
labels.add(%label1name);
labels.add(%label2name);
labels.add(%label3name);
labels.add(%label4name);
But if they are too much, you can run the code before for each one of the panels
I'm supposed to create a magic square in 2D using Windows Forms Application. It should look like this:
However, the user should be able to decide the size of the square (3x3, 5x5, 7x7, etc). I already wrote the code in a Console Application, but I don't know how to add the 2D graphics.
Somebody already asked this question (How do I put my result into a GUI?), and one of the answers was to use DataGridView, but I'm not sure if that's what I'm looking for, since I can't make it look like the picture.
Any ideas or advice?
You can use a TableLayoutPanel and add buttons to panel dynamically.
If you don't need interaction with buttons, you can add Label instead.
Create square dynamically:
public void CreateSquare(int size)
{
//Remove previously created controls and free resources
foreach (Control item in this.Controls)
{
this.Controls.Remove(item);
item.Dispose();
}
//Create TableLayoutPanel
var panel = new TableLayoutPanel();
panel.RowCount = size;
panel.ColumnCount = size;
panel.BackColor = Color.Black;
//Set the equal size for columns and rows
for (int i = 0; i < size; i++)
{
var percent = 100f / (float)size;
panel.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, percent));
panel.RowStyles.Add(new RowStyle(SizeType.Percent, percent));
}
//Add buttons, if you have your desired output in an array
//you can set the text of buttons from your array
for (var i = 0; i < size; i++)
{
for (var j = 0; j < size; j++)
{
var button = new Button();
button.BackColor = Color.Lime;
button.Font = new Font(button.Font.FontFamily, 20, FontStyle.Bold);
button.FlatStyle = FlatStyle.Flat;
//you can set the text of buttons from your array
//For example button.Text = array[i,j].ToString();
button.Text = string.Format("{0}", (i) * size + j + 1);
button.Name = string.Format("Button{0}", button.Text);
button.Dock = DockStyle.Fill;
//If you need interaction with buttons
button.Click += b_Click;
panel.Controls.Add(button, j, i);
}
}
panel.Dock = DockStyle.Fill;
this.Controls.Add(panel);
}
If you need interaction with buttons
void button_Click(object sender, EventArgs e)
{
var button = (Button)sender;
//Instead put your logic here
MessageBox.Show(string.Format("You clicked {0}", button.Text));
}
As an example, you can call
CreateSquare(3);
Screenshot:
You can create a Form and add a TableLayoutPanel with this property
tableLayoutPanel1.Dock = DockStyle.Fill;
tableLayoutPanel1.BackColor = Color.Gold;
and this is the result
When you create Row and Column, to fit correctly set the percentage in this way:
After this you can add a Button or Label in each square.
I am drawing set of Labels dynamically and i want to remove them. I am using the same button to remove and add new Labels. The labels are drawn randomly with random coordinates. But, when i am pressing the button the old Labels should me removed and the new Labels appeared. But, what I am having is that the new labels appears and old Labels appears but empty labels. I want them to be remove at all. See the picture:
//Global Intialization
int xCoor;
int yCoor;
//send the random method
Random coor = new Random();
private void btnRun_Click(object sender, EventArgs e)
{
//Removing the Labels after drawing them in the picBox
this.RemoveOldLabels();
//to draw the Labels rendomely.
for (int x = 1; x <= 25; x++)
{
for (int i = 0; i < 1; i++)
{
//Get the Coordinates for X,Y
xCoor = coor.Next(0, 750);
yCoor = coor.Next(0, 500);
//Start Greating the Labels
Label nodeLabel1 = new Label();
nodeLabel1.Text = x + " : " + xCoor + "," + yCoor;
nodeLabel1.AutoSize = true;
nodeLabel1.Location = new Point(xCoor + 10, yCoor + 5);
nodeLabel1.ForeColor = System.Drawing.Color.Red;
nodeLabel1.BackColor = Color.LightBlue;
//Draw the Labels in the PicBox
this.picNodes.Controls.Add(nodeLabel1);
}
}
}
//this to remove the Labels
private void RemoveOldLabels()
{
List<Label> LabelsToRemove = new List<Label>();
foreach (var x in this.picNodes.Controls)
{
if (x.GetType() == typeof(System.Windows.Forms.Label))
{
LabelsToRemove.Add((Label)x);
}
}
It looks like RemoveOldLabels() is finding the labels, but not actually removing them.
Try getting all "Label" controls, then disposing of them (which should also remove them from the collection and make them disappear off the form).
foreach (var label in picNodes.Controls.OfType<Label>().ToList())
label.Dispose();
Your remove old labels logic does not do anything. It simply adds the labels to a list and that's it.
You need to remove those controls from picNodes as below:
private void RemoveOldLabels()
{
List<Label> LabelsToRemove = new List<Label>();
foreach (var x in this.picNodes.Controls)
{
if (x.GetType() == typeof(System.Windows.Forms.Label))
{
LabelsToRemove.Add((Label)x);
}
}
foreach (var label in LabelsToRemove)
{
this.picNodes.Controls.Remove(label);
label.Dispose();
}
}
I am trying to create trackbars and labels dynamically. In which if a user inputs a number like 4, it creates 4 trackbars and 4 labels. Then if the user moves any of the dynamically created trackbar moves it and updates its associated label. Then adds the numbers in all the labels and stores it in another label call total label.
Here is another way of explaining it. The user enters the number 3. The system creates 3 trackbars and 3 labels (next to the trackbars). The user moves first track bar to 5, the first label is automatically updated with 5. The user moves the second track bar to 3, the second label is automatically updated with 3. finally the user moves the third track bar to position 9 and the label is automatically updated with 9.
On the right side there is another label that shows 17 = (5+3+9).
I found a few websites ons creating dynamically controls but I don't know how to link a dynamically created trackbar to the dynamically created label. Then adding those dynamically added labels.
ALL this in C# on a windows form.
I did something very simliar to the below when creating my labels and trackbars.
for (int i = 0; i < 10; i++)
{
Label label = new Label();
label.Text = i.ToString();
PlaceHolder1.Controls.Add(label);
}
Thanks in advances
------------------------Update-----------------
void CreateLabeledTrackBars(Control host, int n)
how do I use this, I was hoping that when I start a new form
that all I would have to is this..that way the form already has the in n, but it seems not to work..i am confused on how the control works. can you please explain
namespace WindowsFormsApplication1
{
public partial class Form3 : Form
{
public static Form2 myNewForm = new Form2();
private TrackBar[] _trackBars;
private Label[] _labels;
public Form3(int n)
{
CreateLabeledTrackBars(new Label (), n);
}
//Then the rest of the code
You need to handle ValueChanged event of each TrackBar you create. To calculate sum of all values, store created controls in arrays.
private TrackBar[] _trackBars;
private Label[] _labels;
void CreateLabeledTrackBars(Control host, int n)
{
const int trackBarWidth = 150;
const int minValue = 0;
const int maxValue = 10;
const int defaultValue = 0;
_trackBars = new TrackBar[n];
_labels = new Label[n];
int y = 0;
for(int i = 0; i < n; ++i)
{
var label = new Label()
{
Top = y,
Left = trackBarWidth,
Text = defaultValue.ToString(),
Parent = host,
};
var trackBar = new TrackBar()
{
Top = y,
Width = trackBarWidth,
// save associated label
Tag = label,
Minimum = minValue,
Maximum = maxValue,
Value = defaultValue,
Parent = host,
};
// handle ValueChangedEvent
trackBar.ValueChanged += OnTrackBarValueChanged;
// apply vertical offset for next trackbar
y += trackBar.Height;
_trackBars[i] = trackBar;
_labels[i] = label;
}
}
void OnTrackBarValueChanged(object sender, EventArgs e)
{
// get trackbar, which generated event
var trackBar = (TrackBar)sender;
// get associated label
var associatedLabel = (Label)trackBar.Tag;
associatedLabel.Text = trackBar.Value.ToString();
// recalculate sum of all values and update other label here
}
Now, when you have an array of trackbars, getting sum of all values should be trivial.