Fill an Array with Labels - c#

I've currently got 5 labels in a Windows Form on Visual Studio and I need to populate an array with these 5 labels.
The 5 labels are named 'die1', 'die2', 'die3', 'die4', 'die5'
I figured I should be able to generate the array and then use a for loop to populate it, but the for loop is where I get stuck. This is what I have so far:
Label[] labels = new Label[5];
for (int i = 0; i < labels.Length; i++)
labels[i] = new Label(die(i));
Any help would be appreciated!

You can use LINQ to search the collection of controls on the Form, and create an array from any Label's whose name starts with "die":
var labels = Controls.OfType<Label>()
.Where(label => label.Name.StartsWith("die"))
.ToArray();

Label[] lbl ;
private void setupControls()
{
int Totallbl = 5;
int height = 30;
lbl = new Label[Totallbl];
try
{
for (int i = 0; i < Totallbl; i++)
{
lbl[i] = new Label();
lbl[i].Location = new Point(20, ((i + 1) * height));
lbl[i].Name = "lbl" + i;
lbl[i].Text = "LabelText";
lbl[i].AutoSize = true;
this.Controls.Add(lbl[i]);
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
You can call back the label like this:
lbl[0].Text = "Text u want to change"
lbl[1].Text = "Text u want to change"
...

Related

How to edit a control content in an array inside of a list

I got the following:
List<TextBox[]> ListMonths = new List<TextBox[]>();
I use it for store the same textboxes for each month, I fill it like this
for (int i = 0; i <= 11; i++)
{
......
TextBox[] TBaux = new TextBox[18];
for (int o = 0; o <= 17; o++)
{
TBaux[o] = (TextBox)element.FindName("TB" + o + i);
}
ListMonths.Add(TBaux);
}
So that way I got the textboxes for each month in ListMonths.
How can I modify the Text property of one of the textbox (for instance textbox[2]) that is stored in one of the month lists (for instance ListMonths[1])?
ListMonths[1][2].Text = "blabla";
Which is the same as doing:
TextBox[] textBoxes = ListMonths[1];
TextBox textBox = textBoxes[2];
textBox.Text = "blabla";

How to access labels from loop and change their text

I have list where are 6 sentences which I want to put in 6 different labels.
All six labels are named Slot0Sentence, Slot1Sentence, Slot2Sentence...
This is how I loop
for (int i = 0; i < ls.Count; i++)
{
Slot0Sentence.Text = ls[i];
}
However I dont know how to access other labels.
If there would be normal string I would do Slot + i + Sentence but in this case this dont work.
with an array of labels you can control their properties. you don't need design here, you can do that with code.
Label[] l = new Label[6];
int x = 20;
for (int i = 0; i < l.Length; i++)
{
l[i] = new Label();
l[i].Name = "Hello " + i.ToString();
l[i].Text = "Hello " + i.ToString();
l[i].Location = new Point(x, 10);
x += 100;
}
you can change the names and text to whatever you like.
I'd just use Children property of parent container (Grid, StackPanel,..). This gives you a collection which supports indexes. Additionally, in case you have different controls, use if statement
if(element in Label)
{
element.Text = ...
}

C#: Show string variables in WF textboxes

string[] board = new string[9];
for (var i = 0; i < 9; i++)
{
board[i] = (textBox1.Text);
}
I'm trying to make a loop which puts the text of textboxes in the array, but I can't figure out how to put the i variable in the 'textBox.Text' statement. I've tried this:
board[i] = ("textBox" + i + ".Text");
But this returns 'textBox1.Text'. How do I make the textbox.Text statement 'compatible' with the for loop?
You didn't tell us what API are you using as #Jeppe Stig Nielsen commented.
Asp.net? WPF? Windows Forms?
In Asp.net you can use FindControl method
string[] board = new string[9];
for (var i = 0; i < 9; i++)
{
board[i] = ((TextBox)FindControl("textBox" + i)).Text
}
In WPF you can use FindName method:
string[] board = new string[9];
for (var i = 0; i < 9; i++)
{
board[i] = ((TextBox)this.FindName("textBox" + i)).Text;
}
Use more meaningful control names if you want to maintain your code sometime. The business logic should not be dependent on control names.
However, if you want to get an array of all textboxes in a container control like the form you could also use LINQ:
string[] board = this.Controls.OfType<TextBox>()
.Where(txt => txt.Name.StartsWith("textBox"))
.Select(txt => txt.Text)
.ToArray();
If you only want to take textboxes from 1-9:
var txtNames = Enumerable.Range(1, 9).Select(i => "textBox" + i);
string[] board = this.Controls.OfType<TextBox>()
.Where(txt => txtNames.Contains(txt.Name))
.Select(txt => txt.Text)
.ToArray();
Try this ,
string[] arr= new String[3];
for (int i = 0; i <= 2; i++)
{
TextBox testTextBox = (TextBox)this.Controls["textBox" + i.ToString()];
arr[i] = testTextBox.Text;
}

Remove a checkbox that is being created dynamically in a loop

I have a bunch of code that dynamicly creates some controls. It looks in a folder and lists the filenames in it. For each file in the folder it creates a checklistbox item, listbox item and two checkboxes. This is working great and as intended:
private void getAllFiles(string type)
{
try
{
string listPath = "not_defined";
if (type == "internal_mod")
{
int first_line = 76;
int next_line = 0;
int i = 0;
CheckBox[] chkMod = new CheckBox[100];
CheckBox[] chkTool = new CheckBox[100];
listPath = this.internalModsPath.Text;
string[] filesToList = System.IO.Directory.GetFiles(listPath);
foreach (string file in filesToList)
{
if (!internalModsChkList.Items.Contains(file))
{
internalModsChkList.Items.Add(file, false);
string fileName = Path.GetFileName(file);
internalModNameList.Items.Add(fileName);
//-----------------
// Draw Checkboxes
//-----------------
chkMod[i] = new CheckBox(); chkTool[i] = new CheckBox();
chkMod[i].Name = "modChk" + i.ToString(); chkTool[i].Name = "modChk" + i.ToString();
//chkMod[i].TabIndex = i; //chkTool[i].TabIndex = i;
chkMod[i].Anchor = (AnchorStyles.Left | AnchorStyles.Top); chkTool[i].Anchor = (AnchorStyles.Left | AnchorStyles.Top);
chkMod[i].Checked = true; chkTool[i].Checked = false;
chkMod[i].AutoCheck = true; chkTool[i].AutoCheck = true;
chkMod[i].Bounds = new Rectangle(549, first_line + next_line, 15, 15); chkTool[i].Bounds = new Rectangle(606, first_line + next_line, 15, 15);
groupBox7.Controls.Add(chkMod[i]); groupBox7.Controls.Add(chkTool[i]);
//-----------------
next_line += 15;
i++;
}
}
}
Now my problem is that I also want the user to be able to delete all these thing again based on the checklistbox' checked items.. I have no problems deleting the items in the checklistbox or the items in the listbox, but I want to remove the two checkboxes I create too ..
This is what I got to remove the items in the checklistbox, and the listbox
private void internalModListDel_btn_Click(object sender, EventArgs e)
{
int count = internalModsChkList.Items.Count;
for (int index = count; index > 0; index--)
{
if (internalModsChkList.CheckedItems.Contains(internalModsChkList.Items[index - 1]))
{
internalModsChkList.Items.RemoveAt(index - 1);
internalModNameList.Items.RemoveAt(index - 1);
groupBox7.Controls.Remove(modChk[index - 1]);
}
}
}
As you can see I have also tried to write something to remove the checkbox but it doesn't work and I have no idea how to make it work
Can you assist ?
Try using UserControls.
Use the ListBox controller to show those UserControls,
The user control can be built with those checkboxes, and the labels you want .
Another suggestion is to bind this list to an ObservableCollection which will contain the UserContorols you have created.
This way, it will be much more simlpe to add/remove/change the items inside.

How to manipulate controls created at runtime?

Suppose I have this in page load:
Label lblc = new Label();
for (int i = 1; i <= 10; i++)
{
lblc.Text = i.ToString();
this.Controls.Add(lblc);
}
How can I manipulate each of these controls at run time?
I want to:
Set/get their text.
Reference a particular control, in this case Label.
Use an array if you know how many labels you will have,
Label[] lblc = new Label[10];
for (int i = 0; i < 10; i++)
{
lblc[i] = new Label() { Text = (i + 1).ToString() };
this.Controls.Add(lblc[i]);
}
Then you will reference the textbox 1 with lblc[0] and textbox 2 with lblc[1] and so on. Alternatively if you do not know how many labels you will have you can always use something like this.
List<Label> lblc = new List<Label>();
for (int i = 0; i < 10; i++)
{
lblc.Add(new Label() { Text = (i + 1).ToString() });
this.Controls.Add(lblc[i]);
}
You reference it the same way as the array just make sure you declare the List or the array outside your method so you have scope throughout your program.
Suppose you want to do TextBoxes as well as Labels well then to track all your controls you can do it through the same list, take this example where each Label has its own pet TextBox
List<Control> controlList = new List<Control>();
for (int i = 0; i < 10; i++)
{
control.Add(new Label() { Text = control.Count.ToString() });
this.Controls.Add(control[control.Count - 1]);
control.Add(new TextBox() { Text = control.Count.ToString() });
this.Controls.Add(control[control.Count - 1]);
}
Good luck! Anything else that needs to be added just ask.
Your code creates only one control. Because, label object creation is in outside the loop. you can use like follows,
for (int i = 1; i <= 10; i++)
{
Label lblc = new Label();
lblc.Text = i.ToString();
lblc.Name = "Test" + i.ToString(); //Name used to differentiate the control from others.
this.Controls.Add(lblc);
}
//To Enumerate added controls
foreach(Label lbl in this.Controls.OfType<Label>())
{
.....
.....
}
Better to set the Name and then use that to distinguese between the controls
for (int i = 1; i <= 10; i++)
{
Label lblc = new Label();
lblc.Name = "lbl_"+i.ToString();
lblc.Text = i.ToString();
this.Controls.Add(lblc);
}
when:
public void SetTextOnControlName(string name, string newText)
{
var ctrl = Controls.First(c => c.Name == name);
ctrl.Text = newTExt;
}
Usage:
SetTextOnControlName("lbl_2", "yeah :D new text is awsome");

Categories

Resources