Iterating through fields? - c#

First of all, I'm not entirely sure how to phrase this or what to search for if someone asked before.
Say I have multiple labels: label1, label2, label3, label4, etc...
Now, I know this works in PHP so I'm wondering if there is a way to do this in C# -
Can I somehow iterate through these labels to set their values in a loop?
i.e.
string[] something = new string[3] { "text", "text", "text" };
for (int i = 0; i < something.length; i++)
{
labels(i).Text = something[i];
}

You can use Controls.Find() method for finding the Label Control by its Control Name.
Try This:
for (int i = 0; i < something.length; i++)
{
((Label) Controls.Find("lablel"+i,true)[0]).Text = something[i];
}

You can get an enumerable list of labels from the Controls collection by using .OfType<>
e.g.
foreach(Label l in this.Controls.OfType<Label>())
{
...
}

Or simply find all the labels without needing to know their names:
foreach (Control ctrl in this.Controls)
{
Label label = ctrl as Label;
if (label != null)
{
label.Text = "";
}
}

You could use Controls.Find to find all references:
for (int i = 0; i < something.length; i++)
{
var lbl = this.Controls.Find("lable" + i, true);
if(lbl.Length > 0)
((Label)lbl[0]).Text = something[i];
}
Another approach using LINQ (which doesn't search recursively as opposed to Find):
for (int i = 0; i < something.Length; i++)
{
Label lbl = this.Controls.Cast<Label>()
.FirstOrDefault(l => l.Name.Equals("lable" + i, StringComparison.InvariantCultureIgnoreCase));
if(lbl != null) lbl.Text = something[i];
}
However, i would not call this good practise. Your array and the labels are directly related to each other. What hapens if you change the array but forget to change the labels?
You should use a different control like ListBox or DataGridView or create the labels dynamically according to the size of the array.

Related

WPF put XAML refrences into a c# list

Right now I have 15 items, that I have to set the value to one by one, is there a way I can put all the refrences into one c# list or something, so I could loop through it?
//TITLES
BTitle0.Text = Items[14]["title"];
BTitle1.Text = Items[13]["title"];
BTitle2.Text = Items[12]["title"];
BTitle3.Text = Items[11]["title"];
BTitle4.Text = Items[10]["title"];
BTitle5.Text = Items[9]["title"];
BTitle6.Text = Items[8]["title"];
BTitle7.Text = Items[7]["title"];
BTitle8.Text = Items[6]["title"];
BTitle9.Text = Items[5]["title"];
BTitle10.Text = Items[4]["title"];
BTitle11.Text = Items[3]["title"];
BTitle12.Text = Items[2]["title"];
BTitle13.Text = Items[1]["title"];
BTitle14.Text = Items[0]["title"];
Basically I want to have a list to XAML refrences like BTitle[0].text..., Is there any way to do that?
Try the FindName method of the window or control that hosts the TextBox elements:
for (int i = 0; i < 15; i++)
{
TextBox textBox = FindName("BTitle" + i) as TextBox;
if (textBox != null)
{
textBox.Text = "...";
}
}
Or use an ItemsControl that binds to the items.

C# (UWP) - Access object dynamically from string-variable

So I've written some code that creates TextBlocks from a list of strings by calling a for loop:
List<string> menuPages = new List<string>() { "Home", "Media", "Settings" };
//method called from constructor:
private void createHeaders ()
{
for (int i=0; i<menuPages.Count; i++)
{
TextBlock iheader = new TextBlock();
iheader.Name = menuPages[i];
iheader.Text = menuPages[i];
if (i==pageIndex)
{ iheader.FontSize = 36; }
else
{ iheader.FontSize = 32; }
stacky.Children.Add(iheader); //Adding button to stack panel
}
}
Now I've been writing another method that would cycle through each TextBlock in a loop and change the text to whatever I intend. I'd gotten a foreach loop working for the stackPanel children: (TextBlock tBlock in stacky.Children)
but I need to work with an indexed for loop. The code below is how I WANT to achieve this:
//Re-render headers
for (int i = 0; i < menuPages.Count; i++)
{
//TextBlock menuPages[i].text = "foo";
}
Now of course the syntax above doesn't work so my question is, how can I address the TextBlocks from the strings in a list?
Just have your textblocks created in a list. So, you can manipulate easily with indexed forloop.
List<string> menuPages = new List<string>() { "Home", "Media", "Settings" };
List<TextBlock> textBlocks = new List<TextBlock>();
public MainPage()
{
this.InitializeComponent();
createHeaders();
}
private void createHeaders()
{
for (int i = 0; i < menuPages.Count; i++)
{
TextBlock iheader = new TextBlock();
iheader.Name = menuPages[i];
iheader.Text = menuPages[i];
iheader.FontSize = 32;
textBlocks.Add(iheader);
Stacky.Children.Add(iheader);
}
}
private void change_Click(object sender, RoutedEventArgs e)
{
for (int i = 0; i < textBlocks.Count; i++)
{
textBlocks[i].Text = "foo";
}
}
If the StackPanel only contains the TextBlock elements you are adding dynamically, you can access them this way as well:
foreach (var textBlock in Stacky.Children.OfType<TextBlock>())
{
textBlock.Text = "something";
}
This approach uses the OfType<T> LINQ extension method which filters the input collection by the specified type, so it only returns those children of Stacky that are a TextBlock.
If you have more content, in the StackPanel, then #Vignesh G's answer is the way to go.

Variable in C# for loop

I have got many buttons in my Application Form. And I would like to check every buttons text (compare). How can I achive that ?
for (i = 1; i < 30; i++)
{
if (this.button1.Text == "Hello") //here is PROBLEM
{
//..some statement
}
}
So next time this.button1.Text must change to this.button2.Text and so on...
this.button[i].Text not working.
Buttons are not arrays. Each one is a discreet object, and a child of its container.
Ideally, you need to build a collection (array, list, whatever) of the buttons and iterate through that collection, rather than using an index variable (i).
Here's a good approach: https://stackoverflow.com/a/3426721/820068
This is a correct syntax:
foreach (Control button in this.Controls)
{
if (button.GetType() == typeof(Button) && button.Text == "Hello")
{
//..some statement
}
}
I'm quite sure that this is a windows form.
And in windows form you can iterate the controls like this.
foreach (Control c in panel.Controls)
{
string cType = c.GetType().ToString();
// check all buttons
if (cType == "System.Web.UI.WebControls.Button")
{
if(((Button)c).Text == "Hello")
{
}
}
}
So what the code does is to iterate all the controls inside a panel and check each control if it's type is a button.
Update:
As Wesley said, much better approach for the condition is to implement it like this
if (c is Button && c.Text.Equals("Hello")) {
for (int i = 1; i < 3; i++)
{
var buttonName = "button" + i;
Button button = this.Controls.Find(buttonName, true).FirstOrDefault() as Button;
string text = button.Text;
}
try this code.

Count the number of controls - C# with the certain names?

C# - 2.0
I am trying to figure out on how to do a loop on a list of controls with certain names: "txtTesting[i]"
txtTesting1
txtTesting2
txtTesting3 ...
txtTesting13
With the code I have a total of 13. But this can change as time goes by. So I am looking to get the data from the textboxes that have data in them. I just can not seem to figure out a way to do a count of the controls. I have tried this...
for (int i = 1; i < 13; i++)
{
if (txtTesting[i].text != "")
{
//
}
}
I am also getting this error...
Error 51 The name 'txtTesting' does not exist in the current context
Unless I am missing something here.
System.Web.UI.WebControls.TextBox
Assuming this is a System.Windows.Forms application, you should be able to go through all your controls on the form and then select the ones that are TextBox as follows:
foreach (System.Windows.Forms.Control control in this.Controls)
{
if (control is System.Windows.Forms.TextBox)
{
if (((System.Windows.Forms.TextBox)control).Text != "")
{
// Do something
}
}
}
For an asp.net application this would be very similar:
foreach (System.Web.UI.Control control in this.Controls)
{
if (control is System.Web.UI.WebControls.TextBox)
{
if ((System.Web.UI.WebControls.TextBox)control).Text != "")
{
// Do something
}
}
}
txtTesting looks like an array. does it have a Length property?
for (int i = 1; i < txtTesting.Length; i++)
if it's a type List<T> than maybe it has a Count property
for (int i = 1; i < txtTesting.Count; i++)
If you don't already have an array, you can initialize one in your presumed Form's constructor
List<WhateverTypeTxtTestingIs> txtTesting = new List<WhateverTypeTxtTestingIs>();
txtTesting.Add(txtTesting1);
txtTesting.Add(txtTesting2);
...
The most efficient way would be to add the controls to an array and loop over that, but you could also loop through the controls and inspect the control's Name:
foreach(Control c in this.Controls) // <-- "this" may not be appropriate - you just need to reference the containing control
{
if(c.Name.StartsWith("txtTesting")
{
///
}
}
In your constructor, after the call to InitializeComponent, stuff the text boxes in a collection.
// class-scoped variable
private List<Textbox> _boxen = new List<TextBox>();
public MyFormDerp()
{
InitializeComponent();
_boxen.Add(txtTesting1);
// etc
_boxen.Add(txtTesting13);
}
and, later on...
foreach(TextBox box in _boxen)
if (box.text != "")
{
//
}
Also, your design should make you itch.
You can use a foreach over your array:
foreach (TextBox txt in txtTesting)
{
if (txt.text != "")
{
//
}
}
Or, the array has a length property that you can use.
for (int i = 1; i < txtTesting.length; i++)
{
if (txtTesting[i].text != "")
{
//
}
}
If you don't have an array of controls, you may want to look at this answer to loop through all the controls on your form. Except the generic Dictionary isn't in C# 2, so it will look more like this:
private void button1_Click(object sender, EventArgs e)
{
ArrayList txtTesting = ArrayList();
LoopControls(controls, this.Controls);
foreach (TextBox txt in txtTesting)
{
if (txt.text != "")
{
//
}
}
}
private void LoopControls(ArrayList list, Control.ControlCollection controls)
{
foreach (Control control in controls)
{
if (control is TextBox && control.Name.StartsWith("txtTesting"))
list.Add(control);
if (control.Controls.Count > 0)
LoopControls(list, control.Controls);
}
}

ASP.net -- Identifying a specific control in code behind

I have a page that holds 5 texboxes each name similar but with a numerial suffix. Example:
tbNumber1, tbNumber2, tbNumber3 and so on.
The reason it's like that is because those textboxes are generated dynamically based on some parameter. I never know how many textboxes will be need for a particular record.
How can I loop trough the text contents of these texboxes?
MY first instinct was to do something like the following, but that obviously does't work :)
for (int i = 0; i <= 3; i++)
{
string foo = tbNumber+i.Text;
//Do stuff
}
Wahts the best way to go trough each of these textboxes?
Thanks!!!
You might be able to do something like this:
for( int i = 0; i < upperLimit; i++ )
{
TextBox control = Page.FindControl("tbNumber" + i) as TextBox;
if( control != null ) {
// do what you need to do here
string foo = control.Text;
}
}
Possibly try something like
foreach(Control control in Page.Controls)
{
//Do stuff
}
If you're generating them dynamically, put them in a List<TextBox> as you generate them:
// in the Page_Load or whereever you generate the textboxes to begin
var boxes = new List<TextBox>();
for (int i = 0; i < numRecords /* number of boxes */; i++) {
var newBox = new TextBox();
// set properties here
boxes.Add(newBox);
this.Controls.Add(newBox);
}
Now you can loop through the textboxes without using crufty string techniques:
foreach (var box in boxes) {
string foo = box.Text;
// stuff
}
What you need is a recursive FindControl like function. Try something like this:
for (int i=0; i<3; i++)
{
Control ctl = FindControlRecursive(Page.Controls, "tbNumber", i.ToString());
if (ctl != null)
{
if (ctl is TextBox)
{
TextBoxControl tbc = (TextBox)ctl;
// Do Something with the control here
}
}
}
private static Control FindControlRecursive(Control Root, string PrefixId, string PostFix)
{
if (Root.ID.StartsWith(PrefixId) && Root.ID.EndsWith(PostFix))
return Root;
foreach (Control Ctl in Root.Controls)
{
Control FoundCtl = FindControlRecursive(Ctl, PrefixId, PostFix);
if (FoundCtl != null)
return FoundCtl;
}
return null;
}
If you're using a CheckBoxList control you should be able to loop through each checkbox in the control.
foreach(var checkbox in checkboxlistcontrol)
{
string name = checkbox.Text;
}
If you're not using a CheckboxList control, you might want to consider using one as an option.

Categories