Use an int when accessing a name in C# - c#

I'm currently build a windows phone 8 application using c# and I'm wondering how I can achieve this:
for (int i = 1; i <= 18; i++)
{
_(i)Score.Text = "whatever here";
}
which when run should be something like:
_1Score.Text = "whatever here";
_2Score.Text = "whatever here";
_3Score.Text = "whatever here";
etc.
How am I able to achieve this as just putting _(i)Score doesn't work.
EDIT: What im doing is making a scorecard app which has a table overview. I've named each one as 1Socre, 2Score, 3Score etc. and I just want to update what they say. They are all textboxes and I'm just replacing the text inside.
Please Help.
Thanks

This most direct way to implement what you're doing:
var name = string.Format("_{0}Score", i);
this.Controls[name].Text = "...";
Knowing the types (based on #sa_ddam213's comment):
foreach(var textBox in Children.OfType<TextBox>().Where(txt => txt.Name.EndsWith("Score")))
{
textBox.Text = "...";
}

Related

C# Selenium - dropdown menu/ combobox

I have a problem selecting from a custom dropdown menu.. I have tried both by using the XPath, CssSelector and Id.
I have added a link to the code here:
Picture of the code
I think i have to access the div class="SelectBox" in order to access the id='ctl00_ctl00_ctl00_MP_Blank_Body_MP_Base_Body_MP_TopSideMenu_Body_ctl00_cboBehandlingstype'
but i keep getting errors.
This is what I'm currently trying but without any luck:
IWebElement test = driver.FindElement(By.XPath("//div[#class='input']//div[#id='ctl00_ctl00_ctl00_MP_Blank_Body_MP_Base_Body_MP_TopSideMenu_Body_ctl00_cboBehandlingstype']"));
Can someone give me a clue on how to get access to the items in the dropdown?
Thank you! :)
You need to use "SelectElement" instead of "IWebElement".
SelectElement mySelect = new SelectElement(yourDriver.FindElement(By.Id("ctl00_ctl00_ctl00_MP_Blank_Body_MP_Base_Body_MP_TopSideMenu_Body_ctl00_cboBehandlingstype")));
mySelect.SelectByText("510111 Normalbehandling");
Try This
var select = driver.FindElementById("ctl00_ctl00_ctl00_MP_Blank_Body_MP_Base_Body_MP_TopSideMenu_Body_ctl00_cboBehandlingstype");
var stringValues = select.Text.Split(new string[] { "\r\n" }, StringSplitOptions.None);
((IJavaScriptExecutor)driver).ExecuteScript("var select = arguments[0]; for(var i = 0; i < select.options.length; i++){ if(select.options[i].text == arguments[1]){ select.options[i].selected = true; } }", select, stringValues[0]);

C# how to get HTML controls created dynamically

I generated a HTMLTextArea using string and Response.Write():
string area = "<textarea id=\"myArea{0}\" cols=\"30\" name=\"S1\" rows=\"5\" runat=\"server\"></textarea>";
Response.Write(String.Format(area,1));
After this, I don't know how to get the object of this myArea1.
Are there any way I can achieve this goal?
The proper way to add System.Web.UI.HtmlControls. will be,
var newTextArea = new HtmlTextArea()
{
ID = string.Format("myArea{0}", 1),
Name = string.Format("S{0}", 1),
Cols = 30,
Rows = 5
};
Page.Controls.Add(newTextArea);
Then you can access it like,
var myTextArea = Page.FindControl("myArea1") as HtmlTextArea;
You can try this.
HtmlTextArea txt = (HtmlTextArea)(Page.FindControl("myArea1"));
string value = txt.Value;
Refer to this.
You don't really need to access the TextArea object itself if you are only interested in getting the user input, which you should be able to find in Request.Form collection on form submission.

Getting a string to be a variable name

I found this question but it's being used with an XML file so I don't really understand what is going on.
What I want to do is get my list of objects to get populated in my for loop. Right now I have this:
for (int i = 0; i < dogs.Length; i++)
{
dogs[i] = new Dog();
}
dogs[0].PictureBox = picDog0;
dogs[1].PictureBox = picDog1;
dogs[2].PictureBox = picDog2;
dogs[3].PictureBox = picDog3;
I want to do something like this:
for (int i = 0; i < dogs.Length; i++)
{
dogs[i] = new Dog();
dogs[i].PictureBox = StringToVariable("picDog" + i);
}
PictureBox is a property field in case that makes a difference.
StringToVariable() is the thing I don't know about. I don't even know what it would be called to search for it.
It's impossible to say for sure without a good, minimal, complete code example. But I would expect that the following statement should work in your scenario:
dogs[i].PictureBox = (PictureBox)Controls.Find("picDog" + i, true)[0];
That will search the children of the current control (which I assume in this case is your Form subclass) for each control in turn. This is somewhat inefficient, as it has to search the controls collection for each item, but as long as you have a relatively small number of items, this is likely not a problem.
Depending on how your Form is set up, the following might also work:
string prefix = "picDog";
foreach (PictureBox pictureBox in Controls.OfType<PictureBox>())
{
if (pictureBox.Name.StartsWith(prefix))
{
int index;
if (int.TryParse(pictureBox.Name.Substring(prefix.Length), out index))
{
dogs[index] = pictureBox;
}
}
}
That version inspects each child control just once, attempting to parse an index appended to the initial text of "picDog", and if it's successful, using that index to assign to your array directly. This has the advantage of scaling well to larger lists of controls, but may be overkill in your case.
Note that in both of the above examples I've left out any error checking. In either example, you would probably want to add some kind of handling in case (for the first example) the desired control couldn't be found, or (for the second example) if you find a control for which you can't parse the index, or fail to fill in one of the elements of the dogs array.
If for some reason neither of the above examples seem to work for you, please edit your post so that it includes a better code example.
Sometimes a simple solution can work well. How about this?
var picDogs = new [] { picDog0, picDog1, picDog2, picDog3 };
for (int i = 0; i < dogs.Length; i++)
{
dogs[i] = new Dog();
dogs[i].PictureBox = picDogs[i];
}
You could even do this:
var dogs = new [] { picDog0, picDog1, picDog2, picDog3 }
.Select(picDog => new Dog() { PictureBox = picDog })
.ToArray();

Access dynamic object by name in a loop

I am new to c# as am a php / js / html developer.
I have 8 switches named relay_1,relay_2,relay_3 etc etc
I need to be able to change the state of these but I would like to do through a for loop so the number is dynamic.
I have tried various methods but to no avail.
Any help would be greatly appreciated.
This is what I would like ( not correct )
for (int i = 0; i < 8; i++)
{
relay_" + i.IsChecked = true;
}
You cannot generate the name of a variable dynamically, but you can create an array of relay objects (the allRelays variable below), and do your operation in a loop, like this:
var allRelays = new {relay_0, relay_1, relay_2, relay_3, relay_4, relay_5, relay_6, relay_7, relay_8};
foreach (var relay in allRelays) {
relay.IsChecked = true;
}

Dynamic Variable Name Use in C# for WinForms

Not sure what is the best way to word this, but I am wondering if a dynamic variable name access can be done in C# (3.5).
Here is the code I am currently looking to "smarten up" or make more elegant with a loop.
private void frmFilter_Load(object sender, EventArgs e)
{
chkCategory1.Text = categories[0];
chkCategory2.Text = categories[1];
chkCategory3.Text = categories[2];
chkCategory4.Text = categories[3];
chkCategory5.Text = categories[4];
chkCategory6.Text = categories[5];
chkCategory7.Text = categories[6];
chkCategory8.Text = categories[7];
chkCategory9.Text = categories[8];
chkCategory10.Text = categories[9];
chkCategory11.Text = categories[10];
chkCategory12.Text = categories[11];
}
Is there a way to do something like ("chkCategory" + i.ToString()).Text?
Yes, you can use
Control c = this.Controls.Find("chkCategory" + i.ToString(), true).Single();
(c as textBox).Text = ...;
Add some errorchecking and wrap it in a nice (extension) method.
Edit: It returns Control[] so either a [0] or a .Single() are needed at the end. Added.
for(...)
{
CheckBox c = this.Controls["chkCategory" + i.ToString()] as CheckBox ;
c.Text = categories[i];
}
You can do that with reflection. But don't.
It's more proper to instantiate a list of contols, add them programmatically to your form, and index that.
Sometimes it can help to put your controls into an array or collection as such:
Checkbox[] chkCataegories = new Checkbox[] { chkCategory1, chkCategory2 ... };
for(int i = 0; i < chkCategories.Length; i++)
chkCategories[i].Text = categories[i];
As another approach, you can dynamically create your checkboxes at runtime instead of design time:
for(int i = 0; i < categories.Length; i++)
{
Checkbox chkCategory = new chkCategory { Text = categories[i] };
someContainer.Controls.Add(chkCategory);
}
At least with dynamically created controls, you don't need to modify your GUI or your form code whenever you add new categories.
You don't need dynamic for that. Put chkCategory1 - 12 in an array, and loop through it with a for loop. I would suggest you keep it around in a field and initialize it at form construction time, because chkCategory seems to be related. But if you want a simple example of how to do it in that simple method, then it would be something like this:
private void frmFilter_Load(object sender, EventArgs e)
{
var chkCategories = new [] { chkCategory1, chkCategory2, chkCategory3, .......... };
for(int i = 0 ; i < chkCategories.Length ; i++ )
chkCategoies[i].Text = categories[i];
}
You know more about the application, so you could perhaps avoid writing out all the control names - for instance, if they are placed on a common parent control, then you could find them by going through it's children.
No, but you could do something like this (untested, beware of syntax errors):
private readonly CheckBox[] allMyCheckboxes = new CheckBox[] { chkCategory1, chkCategory2, ... }
Then you just need to do
for (i = 0; i < 12; i++) allMyCheckboxes[i].Text = categories[i];
The "this.Controls["chkCategory" + i.ToString()]" and "this.Controls.Find("chkCategory" + i.ToString(), true)" both do not work... the former informs you that the contents of the [] are not an int and the latter that ControlCollection does not contain a definition for Find.
Use "Control myControl1 = FindControl("TextBox2");" instead.
I needed this form as I was looping through another array, extracting values and using them to populate form fields. Much easier to look for label1, label2, label3, etc.

Categories