Rick said:
I have a form that needs to display values from an array on the form; how do
I achieve the following?
If item count in array is < 20 then print
Val1 Val2
Val3 Val4
Val5 Val6
and so on
If items in array is > 20 then print
Val1 Val2 Val3
Val4 Val5 Val6
Val7 Val8 Val9
and so on
The following code works fine and prints values in two columns butI need to
modified it to print in three columns if nItemsCount > 20
{
for (i = 1; i <= nItemsCount; i++) {
if (i % 2) {
nX = nX * 25;
nY = nY - 15;
}
myVal.Name = "myVal" + i;
myVal.Text = sLabel;
myVal.Location = new Point(nX, nY + 15);
Controls.Add(myTextBoxLabel);
}
}
Your question seems a little inconsistent. The example output you give
organizes the data across by columns, then down by rows as each row is
filled. And the code itself doesn't look like it could do anything
close to what you want. But even if we make some assumptions and fix
the computational errors in your example code, the code looks more like
something intended to output the data down by row, then across by column
as each column is filled.
Personally, when dealing with a grid layout, I would prefer to organize
the code with more explicit attention to the row and column:
// input data, initialized as appropriate
object[] rgobjData = …;
// wherever you want the output to start
Point ptOrigin = new Point();
// per "Random"'s example
Point ptOffset = new Point(100, 25);
int ccol = rgobjData.Length > 20 ? 3 : 2;
for (int iobj = 0; iobj < rgobjData.Length; iobj++)
{
Point ptCur = ptOrigin;
ptCur.Offset(
(iobj % ccol) * ptOffset.X,
(iobj / ccol) * ptOffset.Y);
myVal.Name = "myVal" + iobj;
myVal.Text = rgobjData[iobj].ToString();
myVal.Location = ptCur;
Controls.Add(myTextBoxLabel);
}
I find that simply calculating x/y, row/col, whatever directly from the
index is more readable and maintainable than constantly adjusting the
individual coordinates back and forth according to the particular point
within the iteration.
All that said…
Depending on what you really want, you may find that it makes more sense
to use the ListBox control (which can do multi-column output), the
ListView control (which also does multi-column output in "list" mode,
and may provide additional control over the formatting), or the
FlowLayoutPanel control (which allows you to simply add new control
instances, such as TextBox instances, while automatically handling the
organization of the controls in a grid fashion).
Pete