Good Afternoon,
I have a html aspx page that has many many div elements. these div elements for a grid. The size of grid is selected client side and the div element are generated server side through a request. The div elements generated are something like this:
<div id="cell_0_0"></div>
<div id="cell_0_1"></div>
<div id="cell_0_2"></div>
<div id="cell_0_3"></div>
<div id="cell_1_0"></div>
<div id="cell_1_1"></div>
etc...
etc...
when the grid is filled with integer values from the user, the values can be accessed by the server, so the server needs to get the values of these elements. This is simple.
int value1 = cell_0_0.innerHTML;
int value2 = cell_0_1.innerHTML;
The problem is… The amount of divs generated by the server are decided at runtime.
(on client input, e.g. 4×4, 5×5 .. 9×9 grid)
So the divs can range from div id=”cell_0_0″ to div id=”cell_4_4″ or from cell_0_0 to cell_9_9.
Now I could have muliple functions on the server like: (pseudocode)
if grid is 5x5
int value5x5-1 = cell_0_0.innerHTML;
... ...
int value5x5-25 = cell_5_5.innerHTML;
if grid is 9x9
int value9x9-1 = cell_0_0.innerHTML;
... ...
int value9x9-81 = cell_9_9.innerHTML
The problem is… these functions would be HUGE! for a 9×9 grid, there are 81 cells, so thats 81 procedural assisngments!
In javascript, I iterate through the cells using a for loop
for (var i = 0; i < gridSize; i++) {
for (var j = 0; i < gridSize; j++) {
document.getElementById( "cell_" + i + "_" + j );
}
}
// as you can see the cell ids are constructed as the loop progresses, because the parameter is a string
Finally… The question is… is there any way… I can get the server side C# code to dynamically iterate through the cell variables depending on how many cells there are.
If Not… What would be the best method to achieve such a problem?
Sorry for the long ass explanation, wanted to make sure you knew exactly what I was on about!
I know its a weird Question, Sorry if there is any confusion:)
Thanks,
Alex
The first issue is that if you divs don’t have
runat="server"(as in your example) then the c# code cannot identify the instance of the element.Second, For the purpose of convenience, (if you have not already done so), put all of your ‘grid divs’ into a single containing div. This will help group and identify the controls you want on the server. It will end up looking something like this:
(for a 4×4 grid, your question presents only the possibility of an AxA grid, rather than an AxB grid, I will work with that assumption):
Finally, Once you are back on the server (presumably during a postback, but you could invoke this after you finish creating the grid) you can collect all of the divs in a single lamda select (in this case we are using “OfType” and “First” to select desired instances) and then work with them from there like this: