Access variable's value via its string name C# - c#

I want to store a series (six to be precise) of Windows Forms labels in an array. There are six labels, which follow the naming convention orderLabel0, orderLabel1... orderLabel5.
I would like to store the pointers to the orderLabels in an array:
Label[] orderLabels = new Label[6];
for(int index = 0; index < 6; index++)
{
orderLabels[index] = orderLabel + [index]; //Error!
}
The code somehow needs to treat the string as variable name and store them as "labels" rather than string in the orderLabels array. In other words, when orderLabels[0] is accessed, I am actually accessing orderLabel0.
Research here and there have led me to dynamic, Reflection and Dictionary options. However, they all require me to specify the object names (correct me if I am wrong), and I am trying to follow the "Do Not Repeat" yourself rule by not having to specify the object six times.
Please advise, thank you.

You can use the Controls form variable to look up the control by name:
Label[] orderLabels = new Label[6];
for(int index = 0; index < 6; index++)
{
orderLabels[index] = Controls[string.Format("orderLabel{0}", index)] as Label;
}

Related

how can i access a textbox which create dynamically?

when i creat unlimited textbox in gridview dynamically how can i access them?
for example:
int uste_uzaklik = 30;
int nesne = ListBox1.Items.Count;
Array.Resize(ref textboxarray, nesne * nesne);
for (int str = 0; str < nesne; str++)
{
for (int stn = 0; stn < nesne; stn++)
{
textboxarray[idm] = new TextBox();
textboxarray[idm].Font.Bold = true;
textboxarray[idm].Font.Name = "Verdana";
textboxarray[idm].ID = idm.ToString();
textboxarray[idm].ToolTip = textboxarray[idm].ID;
GridView2.Rows[str].Cells[stn + 1].Controls.Add(textboxarray[idm]);
if (str == stn) textboxarray[idm].Enabled = false;
uste_uzaklik += 30;
idm++;
}
}
i add texboxes in gridview...you can imagine a matris...
there is no problem...
but when i access them like this:
if (((TextBox)(GridView2.Rows[str].Cells[stn].FindControl(idm.ToString()))).Text != null)
{
matris[i, j] = Convert.ToInt32(GridView2.Rows[str].Cells[stn].Text);
}
occur an error
Object reference not set to an instance of an object.
how can i solve this problem?
References you have to controls don't cease to exist you add them to another control. You've already created an array of your TextBoxes, and you should use that to access them instead of trying to dig into the GridView in which you've added them every single time you want to change them.
Granted, you're going from a one-dimensional array of TextBoxes to a two-dimensional layout within the GridView, so you'll either have to find some way to establish how the indices match up between the two. Or, more easily, you could just turn textboxarray into a two-dimensional array and just have it exactly match the way it's laid out in the GridView. Either way, I think it'll be a lot less work than having to muck around in the GridView.

I have four webbrowsers, each named web1, web2, etc... How do I use a for loop for them?

I have a for loop, and four webbrowsers. They are called:
Web1
Web2
Web3
Web4
I have a for loop:
for (int i = 1; i <= 4; i++)
I want to write the code once, and have it execute on all four browsers. I thought it was something like this:
web[i.toString()]
However that outputs:
The name "web" does not exist in the current context
How would I do it?
Use an array
var webBrowsers = new[] { Web1, Web2, Web3, Web4 };
for(int i = 0; i < webBrowsers.Length; i++)
{
webBrowsers[i]... // Do something with each
}
In general, whenever you have variables with serial names (like Web1..Web4) that's a good indication that you should probably use an array instead. Personally, I'd refactor the code so that you remove all references to the individual webBrowser controls, and use an array exclusively. However, that's probably beyond the scope of this question.
Further Reading:
Arrays Tutorial (C#)
You would need to recover the control by name, not statically, but dynamically:
var matches = this.Controls.Find(string.Format("Web{0}", i), true);
// this means you can't find that control
if (matches.Length == 0) { continue; }
// now you can cast the first control if you'd like
var web = matches[0] as WebBrowser;

Programatically reference ascending variable names (var1, var2, ... )

I'm currently coding a project that can take up to 200 entries of a specific product, as determined by user input. Basically, my GUI loads, and I use jQuery to dynamically build the entries whenever there is a change to the amount field. When using jQuery, I simply give each of them ids in the form of variable1, variable2, ...., variableX (where X is the amount of entries indicated). Small snippet of code to clarify:
for(var i = 1;i <= amount_selected; i++) {
$('table_name tr:last').after('<tr><td><input type="text" id="variable' + i + '"></td></tr>');
}
Now when I try to move to the back end, I'm trying to reference these variable names by putting them in a list. I went ahead and put them in a list of HtmlInputText, to call the Variable names from the list itself. (This would save having to call all (up to 200) methods manually, which is really not an option).
So what I did (in C#) was:
List<HtmlInputText> listvar = new List<HtmlInputText>();
for(int i = 1; i <= amount_selected; i++) {
string j = "variable" + Convert.ToString(i);
HtmlInputText x = j;
listvar.Add((x));
samplemethod(listvar[i]);
}
But it's not working at all. Does anyone have any ideas as to how this would be done, without doing so manually? I know my logic might be completely off, but hopefully this illustrates at least what I'm attempting to do.
I'm assuming these inputs are in a form? If you're submitting then you can access the text boxes from the Request object:
List<string> results = new List<string>();
for (int i = 1; i <= amount_selected; i++)
{
string s = String.Format("{0}", Request.Form["variable" + Convert.ToString(i)]);
results.Add(s);
}
you could do $("#variable" + Convert.ToString(i)).val()

C# - can you name a matrix with the contents of a string

Basically I have x amount of matrices I need to establish of y by y size. I was hoping to name the matrices: matrixnumber1 matrixnumber2..matrixnumbern
I cannot use an array as its matrices I have to form.
Is it possible to use a string to name a string (or a matrix in this case)?
Thank you in advance for any help on this!
for (int i = 1; i <= numberofmatricesrequired; i++)
{
string number = Convert.ToString(i);
Matrix (matrixnumber+number) = new Matrix(matrixsize, matrixsize);
}
You can achieve a similar effect by creating an array of Matrices and storing each Matrix in there.
For example:
Matrix[] matrices = new Matrix[numberofmatricesrequired];
for (int i = 0; i < numberofmatricesrequired; i++)
{
matrices[i] = new Matrix(matrixsize, matrixsize);
}
This will store a bunch of uniques matrices in the array.
If you really want to you could create a Dictionary<String, Matrix> to hold the matrices you create. The string is the name - created however you like.
You can then retrieve the matrix by using dict["matrix1"] (or whatever you've called it).
However an array if you have a predetermined number would be far simpler and you can refer to which ever you want via it's index:
Matrix theOne = matrix[index];
If you have a variable number a List<Matrix> would be simpler and if you always added to the end you could still refer to individual ones by its index.
I'm curious why you cannot use an array or a List, as it seems like either of those are exactly what you need.
Matrix[] matrices = new Matrix[numberofmatricesrequired];
for (int i = 0; i < matrices.Length; i++)
{
matrices[i] = new Matrix(matrixsize, matrixsize);
}
If you really want to use a string, then you could use a Dictionary<string, Matrix>, but given your naming scheme it seems like an index-based mechanism (ie. array or List) is better suited. Nonetheless, in the spirit of being comprehensive...
Dictionary<string, Matrix> matrices = new Dictionary<string, Matrix>();
for (int i = 1; i <= numberofmatricesrequired; i++)
{
matrices.Add("Matrix" + i.ToString(), new Matrix(matrixsize, matrixsize));
}

Get Index of Control in an Control-Array

I have a TextBox Array
private TextBox[,] Fields = new TextBox[9, 9];
and all the TextBoxes have got the same TextChanged-Event
void Field_Changed( object sender, EventArgs e )
Is there a way to get the Index of the sender in the Array (without giving each TextBox it's own EventHandler)?
Do you really need the index, the sender is a reference to the instance that send the request.
If the answer to 1 is yes, you can put the index in the 'Tag' property of the textbox and then query that.
Alternatively you can search the array for the instance that matches the sender argument of the event.
You'll pretty much have to loop through your array and do a reference equality check on each text box.
Either that or assign the index to the tag when you insert the controls to the array. But this is a micro optimization not really worth it.
Try giving each textbox it's own Tag or Name on initialization, Then you can cast sender to a TextBox and look at either of those properties.
You can iterate through the objects and find the one whose reference equals the sender:
for (int i = 0; i < 9; i++)
{
for (int j = 0; j < 9; j++)
{
if (Object.ReferenceEquals(sender, Fields[i, j]))
Console.WriteLine(i + " " + j);
}
}
Taking an eye out the Array Members might help.
The ones you're particularly looking for are the IndexOf() methods. There are multiple overloads. Choose the one that best suits your needs.

Categories