in my project i have 8 dynamic Textboxes and 8 dynamic Labels, which were created in c#.
Now i need to read the text in it and insert it in a db.
My current script looks like
Label labelname1 = this.Controls.Find("label1", false).FirstOrDefault() as Label;
Label labelname2 = this.Controls.Find("label2", false).FirstOrDefault() as Label;
Label labelname3 = this.Controls.Find("label3", false).FirstOrDefault() as Label;
.....
Is it possible, to create a while loop with a variable like:
int i = 1;
while (a < 9)
{
label Labelname+i = this.Controls.Find("label+i" + a, false).FirstOrDefault() as Label;
i++;
}
When I take the "labelname+i" it's not possible, because it isn't a string.
Thank you
Extract method then
private T FindControl<T>(string name) where T : Control {
return this
.Controls
.Find(name, false)
.OfType<T>()
.FirstOrDefault();
}
and use it in a loop (it seems you want for one):
for (int i = 1; i < 9; ++i) {
Label myLabel = FindControl<Label>($"label{i}");
if (myLabel != null) {
//TODO: Put relevant code here
}
}
Same loop if you want to enumerate TextBoxes:
// textBox1..textBox8
for (int i = 1; i < 9; ++i) {
TextBox myTextBox = FindControl<TextBox>($"textBox{i}");
if (myTextBox != null) {
//TODO: Put relevant code here
}
}
You can create a List of Labels and try like:
List<Label> labels = new List<Labels>();
for (int i=1;i<9;i++)
{
Label lbl = this.Controls.Find("label"+i.ToString(), false).FirstOrDefault() as Label;
labels.Add(lbl);
}
And if you want to access i Label you simply do:
labels[i] ...
Related
Can something like this be done?
var test = 1;
label+test+.Text = "Some text goes here...";
Which would result in:
label1.Text = "Some text goes here...";
I wouldn't mind using switch-case if I had few cases, but I have like 40 labels that I would like dynamically assigned text depending on the variable value.
Use Controls.Find() in your form.
void Button1Click(object sender, EventArgs e)
{
var test = 1;
var labels = Controls.Find("label" + test, true);
if (labels.Length > 0)
{
var label = (Label) labels[0];
label.Text = "Some text goes here...";
}
}
var test = 1;
Control label = this.FindControl("label" + test);
if(label != null)
{
label.Text = "Some text goes here...";
}
More informationon FindControl is available at,
https://msdn.microsoft.com/en-us/library/system.web.ui.control.findcontrol%28v=VS.100%29.aspx?f=255&MSPPError=-2147217396
I have like 40 labels that I would like dynamically assigned text
depending on the variable value
Here's another example, which is basically the same approach as Handoko's:
for(int i = 1; i <= 40; i++)
{
Label lbl = this.Controls.Find("label" + i.ToString(), true).FirstOrDefault() as Label;
if (lbl != null)
{
lbl.Text = "Hello Label #" + i.ToString();
}
}
I have a List object that gets automatically filled with the names of textboxes. Now I'd like to cycle through all these text boxes.
How can I let C# know that the string-names in the List are actually TextBox objects with that string-name?
List<string> txtOppsNames = new List<string>();
for (int i = 1; i < numOpps; i++)
{
txtOppsNames.Add("txtOpp" + i);
}
foreach (var txtName in txtOppsNames)
{
if (txtName.Text != "")
{
// do stuff
}
}
The current code reads txtName as a string. I would like it to read as a TextBox.
Edit - the below code contains the solution for me.
List<string> txtOppsNames = new List<string>();
for (int i = 1; i < numOpps; i++)
{
txtOppsNames.Add("txtOpp" + i);
}
foreach (var txtName in txtOppsNames)
{
TextBox textBox = this.Controls.Find(txtName, true).FirstOrDefault() as TextBox;
if (textBox.Text != "")
{
MessageBox.Show("Thanks Amir Popovich");
}
}
Try this :
List<string> txtOppsNames = new List<string>();
for (int i = 1; i < numOpps; i++)
{
txtOppsNames.Add("txtOpp" + i);
}
foreach (var txtName in txtOppsNames)
{
var cntrl= FindControl(txtName);
if (cntrl!=null && cntrl is TextBox)
// do something with
((TextBox)cntrl)
}
Use Control.ControlCollection.Find:
string textBoxName = "txtOpp1";
TextBox textBox = this.Controls.Find(textBoxName, true).FirstOrDefault() as TextBox;
In your case:
List<string> txtOppsNames = new List<string>();
for (int i = 1; i < numOpps; i++)
{
txtOppsNames.Add("txtOpp" + i);
}
foreach (var txtName in txtOppsNames)
{
var control = this.Controls.Find(txtName, true).FirstOrDefault();
if(control != null && control is TextBox)
{
TextBox textBox = control as TextBox;
if(textBox.Text != string.Empty)
{
//logic
}
}
}
Assuming it is Winform, There seems to be no pretty way to do it.
But you could use Loop through Textboxes.
once you have the text box collection, check the names with your string.
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");
Hello I am having trouble with an iteration through a list of 17 labels:
for (int i = 0; i < labels.Count - 1; i++)
{
MessageBox.Show(labels[i].Name);
if (labels[i].Visible == false && labels[i + 1].Visible == true)
{
...
Here are the results I get:
First it goes from label10 to label17, and then in descending order from label9 to label2.
Here is how I add the labels to the list:
private void newGameToolStripMenuItem_Click(object sender, EventArgs e)
{
foreach (Control c in this.Controls)
{
if (c is Label)
{
labels.Add(c);
c.Enabled = true;
if (c.Visible == false)
{
c.Visible = true;
}
}
}
}
I want it to go from label1 to label16, since the loop is just a loop I guess the problem lies in the order in which the labels were added to the list, but I am not sure how to fix it.
Your main problem is lexicographic order which is inherently used when you sort by Name of the label, what you want is to sort by numbers after the term label. In that case, first sort the labels list and then run the for statement over it, check the code:
var lst = labels.OrderBy(x => int.Parse(x.Name.Substring("label".Length))).ToList();
for (int i = 0; i < lst.Count - 1; i++)
{
MessageBox.Show(lst[i].Name);
...
But have in mind that this code is simple and presumes that label Name property always starts with "label" string. If that can change you must handle that case.
I guess you want to sort the labels according to their names?
labels.Sort((x, y) => { return x.Name.CompareTo(y.Name); });
but what are the difference between:
Show "Label 1" first, then "Label 2", and
Show "Label 2" first, then "Label 1"?
Check the designer.cs file to see in which order the labels are added to the Form
assuming that you have Labels id as Label1,Label2..........,Label16
in order to get the labels serially you have to write the following code
labels = labels.ConvertAll<Control>(GetIdFromLabel);
labels.Sort((x, y) => { return x.Id.CompareTo(y.Id); });
public Control GetIdFromLabel(Control c)
{
c.Id = c.Name.Replace("Label", "") == "" ? 0 : Convert.ToInt32(c.Name.Replace("Label", ""));
return c;
}
add this class in your code also
public class Control
{
public string Name { get; set; }
public int Id { get; set; }
}
Try this out:
private void newGameToolStripMenuItem_Click(object sender, EventArgs e)
{
labels.Clear();
Control[] matches;
for (int i = 1; i <= 16; i++)
{
matches = this.Controls.Find("label" + i.ToString(), true);
if (matches.Length > 0 && matches[0] is Label)
{
Label lbl = (Label)matches[0];
labels.Add(lbl);
lbl.Enabled = true;
if (lbl.Visible == false)
{
lbl.Visible = true;
}
}
}
}
I have a simple for loop as follows:
for (int i = 0; i > 20; i++)
{
}
Now I have 20 labels (label1, label2, label3 and so on..)
I would like to do something like:
for (int i = 0; i > 20; i++)
{
label[i].Text = String.Empty;
}
What is the easiest way to accomplish this?
If your labels are placed on one container, say Form, you may do the following:
foreach(Label l in this.Controls.OfType<Label>())
{
l.Text = string.Empty;
}
Same for any other container, say, Panel or GroupBox, just replace this with the name of the container (panel1.Controls, etc.)
I'd call your solution a design-flaw, but I'd go for something like this:
var itemArray = this.Controls.OfType<Label>();
foreach(var item in itemArray)
{
item.Text = string.Empty;
}
Create an array or list of labels and loop through that list to set the properties of each label
List<Label> labels = new List<Label>();
labels.Add(label1);
foreach(Label l in labels)
{
l.Text = String.Empty;
}
Don't know if its the easiest, it is the shortest though..
this.Controls.OfType<Label>().ToList().ForEach(lbl => { lbl.Text = String.Empty; });
Maybe you can use FindControl with something like
for(int i = 0; i < 5; i++)
{
(FindControl("txt" + i.ToString())).Text = String.Emty;
}