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.
Related
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;
}
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 a C# application in which there are several textboxes with the same name except for a number on the end which starts at 1 and goes to 19. I was hoping to use a for loop to dynamically add values to these text boxes by using an arraylist. There will be situations where there will not be 19 items in the arrayList so some text boxes will be unfilled. Here is my sample code for what I am trying to do. Is this possible to do?
for (int count = 0; count < dogList.Count; count++)
{
regUKCNumTextBox[count+1].Text=(dogList[count].Attributes["id"].Value.ToString());
}
So you've got a collection of text boxes that are to be filled out top-to-bottom? Then yes, a collection of TextBox seems appropriate.
If you stick your TextBox references in an array or a List<TextBox> -- I wouldn't use an ArrayList as it's considered deprecated in favor of List<T> -- then yes, you can do that:
TextBox[] regUKCNumTextBox = new []
{
yourTextBoxA,
yourTextBoxB,
...
};
Then yes your logic is possible, you can also query the control by it's name, though that would be heavier at runtime - so it's a tradeoff. Yes, in this solution you must set up a collection to hold your text box references, but it will be more performant.
Try this:
(By the way I am assuming you use WinForms)
for (int count = 0; count < dogList.Count; count++)
{
object foundTextBox = this.Controls.Find("nameofTextBoxes" + [count+1]);
if (foundTextBox != null)
{
if (foundTextBox is TextBox)
{
((TextBox)foundTextBox).Text=(dogList[count].Attributes["id"].Value.ToString());
}
}
}
With this code you are trying to find a Control form your Forms Controls collection. Then you have to make sure the control is of the TextBox type. When it is; cast it to a TextBox and do what you want with it. In this case; assign a value to the Text property.
It would be more efficient to keep a collection of your TextBoxes like in the solution offered by James Michael Hare
Yikes; something doesn't seem quite right with the overall design there; but looking past that, here's a quick stab at some pseudo code that might work:
for (int count = 0; count < dogList.Count; count++)
{
var stringName = string.Format("myTextBoxName{0}", count);
var ctrl = FindControl(stringName);
if(ctrl == null) continue;
ctrl.Text = dogList[count];
}
Ok so I am making a sudoku solver for fun (yes I know it's already been made many times over) so to let people input there values before solving I used numericalupdown (81 one of them to be exact)
and i wanted to assign all of them to an array:
int[,] Sudoku = new int[9, 9];
and then on clicking "solve" the first thing it's supposed to do is put all the values in the array:
private void button1_Click(object sender, EventArgs e)
{
for (int x = 0; x < 81; x++)
{
for (int y = 0; y < 9; y++)
{
if (x-1 == 0)
{
Sudoku[x - 1, y - 1] = Convert.ToInt32(numericUpDown[y].Value);
}
else
{
Sudoku[x - 1, y - 1] = Convert.ToInt32(numericUpDown[x][y].Value);
}
}
}
}
obviously you can't do: "numbericupdown[y]" but thats for you to see what I am trying to do....
sooooo thoughts?
THANKS,
Craiggles
If you put your numericUpDown controls into a 9x9 grid just like you have for the results, then copying the values will be straightforward.
private void button1_Click(object sender, EventArgs e)
{
for (int x = 0; x < 9; x++)
{
for (int y = 0; y < 9; y++)
{
Sudoku[x, y] = Convert.ToInt32(numericUpDown[x, y].Value);
}
}
}
If the controls are actually all dropped onto the form, then don't do that, remove them from the form. Use code to create them, place them programmatically, and put them into a 2d array. Since this is a learning program anyways, that's good practice for doing GUI's programmatically instead of just by drag-n-drop.
I would go about constructing/placing them dynamically and at the same time putting them into an array or list, but if they are already laid out onto a form you can just add them to a generic list to iterate over them.
List<NumericUpDown> nums = new List<NumericUpDown>();
nums.add(numericUpDwown1);
then you could calculate nums[1]*nums[9]... or whatever
I think I understand what you are doing... Two suggestions: 1) put all of your controls into an array of NumericaUpDown objects. Then you could do numericUpDown[y].Value. Otherwise, 2) name the controls ending with numbers (or some similar convention) then use reflection to find the right one and get its value.
Actually there is no reason at all why you cannot create controls and store them in various collection classes - not just arrays.
I would consider putting these into some sort of structured set of collections that reflect the structure of a sudoku grid.
You could dynamically create and place the controls on the form as well as holding them in the collection.
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()