how to get array button to a place on form? - c#

private Button[,] arrButton = new Button[10, 10];
for (int i = 0; i < 10; i++)
{
for (int j = 0; j < 10; j++)
{
arrButton[i, j] = new Button();//getting System.IndexOutOfRangeException
arrButton[i, j].Size = new Size(30, 30);
arrButton[i, j].Location = new Point(i * 30, j * 30);
arrButton[i, j].Click += new EventHandler(arrButton_Click);
this.Controls.Add(arrButton[i, j]);
}
}
this.ClientSize = new Size(300, 300);
After create, array button come up top left corner on form.
how to get array button to a place on form

#choz comment is correct, but a couple things to also consider.
Put the row value and column value in constant variables and use the variables, instead of directly using a number repeatedly.
Example:
private const ROW = 10;
private const COL = 10;
private Button[,] arrButton = new Button[ROW, COL];
...
for (int i = 0; i < ROW; i++)
{
// Change from your code -|
// |----------
// V
for (int j = 0; j < COL; j++)
{
// Create your buttons
}
}
If you are going to use constant numerals, then reference the GetUpperBound() from your array to know the last index value of each dimension.
Example:
private Button[,] arrButton = new Button[10, 10];
...
// GetUpperBound(0) = last index of rows (9 in this case)
for (int i = 0; i <= arrButton.GetUpperBound(0); i++)
{
// Change from your code -|
// |----------
// V GetUpperBound(1) = last index of columns (9 in this case)
for (int j = 0; j <= arrButton.GetUpperBound(1); j++)
{
// Create your buttons
}
}

Syntax error! Your second loop should be:
for (int j = 0; j < 10; j++)
You put "i" instead of "j",

Normally, when you get an System.IndexOutOfRangeException. The debugger error is telling you that the loop or loops you are using are counting the elements more than you specific. Check The count of elements you tinkering with.

I think you are making a mistake in inner loop. Can you please paste this and try to run:
private Button[,] arrButton = new Button[10, 10];
for (int i = 0; i < 10; i++)
{
for (int j = 0; j < 10; j++)//Changed i to j
{
arrButton[i, j] = new Button();
arrButton[i, j].Size = new Size(30, 30);
arrButton[i, j].Location = new Point(i * 30, j * 30);
arrButton[i, j].Click += new EventHandler(arrButton_Click);
this.Controls.Add(arrButton[i, j]);
}
}
this.ClientSize = new Size(300, 300);

Related

ListBox.DataSource doesn't show data on the list

Help guys, I have a List of Points List points = new List(); , what I'm trying to do is removing some data from the list. I used a listbox to see whether it works. This is my code:
points.Add(new PointF(50, 100));
points.Add(new PointF(50, 100));
points.Add(new PointF(200, 300));
points.Add(new PointF(100, 200 ));
points.Add(new PointF(50, 100));
points.Add(new PointF(100, 200));
points.Add(new PointF(200, 300));
points.Add(new PointF(100, 200));
points.Add(new PointF(200, 300));
listBox1.DataSource = points;
float[] sumofxandy = new float[points.Count()];
for (int x = 0; x < points.Count(); x++)
{
sumofxandy[x] = points.ElementAt(x).X + points.ElementAt(x).Y;
}
//code that removes data from list starts from here
float[] difference = new float[points.Count()]; //there is something wrong with this and I don't know what. It has no error but it doesn't make my list to be shown in the listbox.
for (int i = 0; i <= points.Count(); i++)
{
for (int j = 1; j <= points.Count(); j++)
{
difference[j] = sumofxandy[i] - sumofxandy[j];
if (difference[i] == 0)
{
points.RemoveAt(j);
MessageBox.Show("removed");
}
}
} // ends here
listBox2.DataSource = points;
When I erased the code that removes data from the list, the elements inside the list will be shown in the listbox. Help guys
Try changing your for loops as follows (from <= to <). I think you are getting a hidden IndexOutOfBoundsException.
for (int i = 0; i < points.Count(); i++)
{
for (int j = 1; j < points.Count(); j++)
Notice that you are modifying the very same list you are iterating over. This may just as easy remove all the points. You should better create a new list for points that should be removed:
//code that removes data from list starts from here
List<PointF> pointsToRemove = new List<PointF>();
float[] difference = new float[points.Count()];
for (int i = 0; i <= points.Count(); i++)
{
for (int j = 1; j <= points.Count(); j++)
{
difference[j] = sumofxandy[i] - sumofxandy[j];
if (difference[i] != 0)
{
pointsToRemove.Add(points[j]);
MessageBox.Show("removed");
}
}
}
listBox2.DataSource = points.Except(pointsToRemove).ToList();
Could it be that you are using the wrong variable in the if(difference[i] == 0)?
When using your solution I get an ArgumentOutOfRangeException on the line points.RemoveAt(j);
difference[j] = sumofxandy[i] - sumofxandy[j];
if (difference[i] == 0)
{
points.RemoveAt(j);
MessageBox.Show("removed");
}
When the line if(difference[i] == 0) are changed to:
if(difference[j] == 0)
then the code executes successful, with 3 items in listbox2.
EDIT:
As #wdosanjos mentions, you should do your loops with a < rather than <= since you start counting at zero, and not 1. The last element is really at position Count - 1, since the list are zero indexed.
EDIT:
When I changed the loops to: (notice the change in <= to <, it does not throw an exception.)
for (int i = 0; i < points.Count(); i++)
{
for (int j = 1; j < points.Count(); j++)
{
difference[j] = sumofxandy[i] - sumofxandy[j];
if (difference[i] == 0)
{
points.RemoveAt(j);
MessageBox.Show("removed");
}
}
} // ends here
This returns two elements.

margin of buttons in windows phone apps

I am dynamically generating a matrix of buttons(dynamic gridSize),everything is perfect except that I am unable to get them without spaces between them.I tried but could not understand how to use margin attribute.
460 is the width and height of gridPanel over which I am adding buttons
Here is the code from my app.cs file
private void generateButtons()
{
for (int i = 0; i < gridSize; i++)
{
for (int j = 0; j < gridSize; j++)
{
buttons[i, j] = new Button();
buttons[i, j].Content = "0";
buttons[i, j].FontSize = 16;
buttons[i, j].Height = 460/gridSize;
double size = buttons[i, j].Height;
buttons[i, j].Width = 460/gridSize;
buttons[i, j].Foreground = new SolidColorBrush(Colors.Transparent);
opened[i, j] = false;
buttons[i, j].Margin = new Thickness(0 + (size * j), 0 + (size * i), 464 - (0 + (size * (j + 1))), 464 - (0 + (size * (i + 1))));
buttons[i, j].Click += new RoutedEventHandler(cell_Click);
this.gridPanel.Children.Add(buttons[i, j]);
}
}
}
Most 'input controls' (buttons, textboxes etc) on Windows Phone have default spacings equal to 6.0 or 12.0. The simple workaround is to adjust margins of button by -12.
Sugestion unrelated to the question - when you want to populate a Grid uniformally with buttons, it would be perhaps easier, to generate a desired number of rows and columns and put every button in the different cell (with button.margin always equal to -12). All sizing calculations would be done by the Grid. Like this (gridPanel is Grid).
// generate rows and columns
for (int i = 0; i < gridSize; i++)
{
gridPanel.RowDefinitions.Add(new RowDefinition());
gridPanel.ColumnDefinitions.Add(new ColumnDefinition());
}
for (int i = 0; i < gridSize; i++)
{
for (int j = 0; j < gridSize; j++)
{
buttons[i, j] = new Button
{
Content = "0",
FontSize = 16,
Foreground = new SolidColorBrush(Colors.Transparent),
// all buttons have the same margin, no calculation needed
Margin = new Thickness(-12)
};
// placing in a row and column via attached properties
buttons[i, j].SetValue(Grid.RowProperty, i);
buttons[i, j].SetValue(Grid.ColumnProperty, j);
buttons[i, j].Click += new RoutedEventHandler(cell_Click);
opened[i, j] = false;
this.gridPanel.Children.Add(buttons[i, j]);
}
}

Index was outside the bounds of the array confusion

I am trying to learn two dimensional array and I wrote some basic code, but I am getting this exception. Could you tell me what am I doing wrong?
static void Main(string[] args)
{
Random rnd = new Random();
int[,] array = new int[2, 2];
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < 2; i++)
{
array[i, j] = rnd.Next(0, 100);
}
}
for (int i = 0; i < array.GetLength(0); i++)
{
Console.WriteLine(array[i, 0] + "---" + array[i, 1]);
}
Console.ReadLine();
}
The problem is in your inner for-loop. In the iterator section, you're incrementing the i variable, but it should be j. Try this:
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < 2; j++)
{
array[i, j] = rnd.Next(0, 100);
}
}

How to assign a value to an Array in a for- loop

First time the loop is being executed:
A value is assigned to PlaatSnoepArray[0,0] and PlaatSnoepArray[0,1].
Second time the loop is being executed:
A value is assigned to PlaatSnoepArray[1,0] and PlaatSnoepArray[1,1]
AND the values of PlaatSnoepArray[0,0] and PlaatSnoepArray[0,1] are set to 0.
Third time the loop is being executed:
A value is assigned to PlaatSnoepArray[2,0] and PlaatSnoepArray[2,1].
AND the values of PlaatSnoepArray[1,0] and PlaatSnoepArray[1,1] are set to 0.
How can i prevent that the values are set back to 0 ?
static Random Rangen = new Random();
static void PlaatsSnoep(int aantal)
{
for (int i = 0; i < aantal; i++)
{
int SnoepX = Rangen.Next(25, 94);
int SnoepY = Rangen.Next(3, 23);
Console.SetCursorPosition(SnoepX, SnoepY);
Console.WriteLine("0");
int[,] PlaatssnoepArray = new int[aantal,2];
PlaatssnoepArray[i, 0] = SnoepX;
PlaatssnoepArray[i, 1] = SnoepY;
}
Create the array outside the for loop:
int[,] PlaatssnoepArray = new int[aantal,2];
for (int i = 0; i < aantal; i++)
{
int SnoepX = Rangen.Next(25, 94);
int SnoepY = Rangen.Next(3, 23);
Console.SetCursorPosition(SnoepX, SnoepY);
Console.WriteLine("0");
PlaatssnoepArray[i, 0] = SnoepX;
PlaatssnoepArray[i, 1] = SnoepY;
}
How can i prevent that the values are set back to 0 ?
You need to move the creation of the PlaatssnoepArray outside the loop. Currently, each iteration assigns to its own instane of int[aantal,2], which goes out of scope and gets thrown away as soon as the loop iteration is over.
int[,] PlaatssnoepArray = new int[aantal,2];
for (int i = 0; i < aantal; i++)
{
// The rest of your code
}
Your array declaration is inside the loop, move it outside.
int[,] PlaatssnoepArray = new int[aantal,2];
for (int i = 0; i < aantal; i++)
{
int SnoepX = Rangen.Next(25, 94);
int SnoepY = Rangen.Next(3, 23);
Console.SetCursorPosition(SnoepX, SnoepY);
Console.WriteLine("0");
PlaatssnoepArray[i, 0] = SnoepX;
PlaatssnoepArray[i, 1] = SnoepY;
}
You are initializing your array inside the loop, move it out
static Random Rangen = new Random();
static void PlaatsSnoep(int aantal)
{
int[,] PlaatssnoepArray = new int[aantal,2];
for (int i = 0; i < aantal; i++)
{
int SnoepX = Rangen.Next(25, 94);
int SnoepY = Rangen.Next(3, 23);
Console.SetCursorPosition(SnoepX, SnoepY);
Console.WriteLine("0");
PlaatssnoepArray[i, 0] = SnoepX;
PlaatssnoepArray[i, 1] = SnoepY;
}
}
And what about using a List<Point>() instead of an array?
List<Point> PlaatssnoepList = new List<Point>();
for (int i = 0; i < aantal; i++)
{
Point p = new Point(Rangen.Next(25, 94), Rangen.Next(3, 23));
Console.SetCursorPosition(p.X, p.Y);
Console.WriteLine("0");
PlaatssnoepList.Add(p)
}
Take your array out of the loop..

How to add a matrix of OvalShapes to the window?

I want to draw 16*64 matrix, each one containing a:
Microsoft.VisualBasic.PowerPacks.OvalShape.
I used this:
List<Microsoft.VisualBasic.PowerPacks.OvalShape> ovalShape =
new List<Microsoft.VisualBasic.PowerPacks.OvalShape>();
for (int i = 0; i < 16; i++)
{
for (int j = 0; j < 64; j++)
{
OvalShape ovl = new OvalShape();
ovl.Width = 20;
ovl.Height = 20;
ovl.FillStyle = FillStyle.Solid;
ovl.FillColor = Color.Green;
ovalShape.Add(ovl);
}
}
How can I show it in the Window?
Creating a separate container for each shape is not required. Also you can skip the additional container list for the shapes. So you could use this very compact code.
var ovalShapes = new Microsoft.VisualBasic.PowerPacks.ShapeContainer()
{
Dock = DockStyle.Fill,
Margin = new Padding(0),
Padding = new Padding(0),
};
for (int i = 0; i < 16; i++)
for (int j = 0; j < 64; j++)
ovalShapes.Shapes.Add(
new Microsoft.VisualBasic.PowerPacks.OvalShape()
{
Width = 20,
Height = 20,
FillStyle = Microsoft.VisualBasic.PowerPacks.FillStyle.Solid,
FillColor = Color.Green,
Location = new Point(20 * i, 20 * j),
});
this.Controls.Add(ovalShapes);
From MSDN:
An OvalShape control cannot be displayed directly on a form or
container control; it must be contained in a ShapeContainer object.
After you initialize an OvalShape, you will have to set its Parent
property either to an existing ShapeContainer or to a new instance of
ShapeContainer.
Try to set Location and add your controls to the Form:
List<Microsoft.VisualBasic.PowerPacks.OvalShape> ovalShape = new List<Microsoft.VisualBasic.PowerPacks.OvalShape>();
for (int i = 0; i < 16; i++)
{
for (int j = 0; j < 64; j++)
{
OvalShape ovl = new OvalShape();
ovl.Width = 20;
ovl.Height = 20;
ovl.FillStyle = FillStyle.Solid;
ovl.FillColor = Color.Green;
ovl.Location = new Point(ovl.Width*i, ovl.Height*j);
ovalShape.Add(ovl);
}
}
foreach(OvalShape os in ovalShape)
{
Microsoft.VisualBasic.PowerPacks.ShapeContainer shapeContainer = new Microsoft.VisualBasic.PowerPacks.ShapeContainer();
Control c = new Control();
shapeContainer.Parent = c;
os.Parent = shapeContainer;
myForm.Controls.Add(c);
}
First simplify
int totalCount = 1024; //16*64
const int shapeWidth =20;
const int shapeHeight = 20;
for (int j = 0; j < totalCount; j++)
{
OvalShape ovl = new OvalShape();
ovl.Width = shapeWidth;
ovl.Height = shapeHeight;
ovl.FillStyle = FillStyle.Solid;
ovl.FillColor = Color.Green;
ovalShape.Add(ovl);
}
After pickup your drawing area and decide how much shapes per row you would like to have.
So some hypothetical code could look like this:
int shapesPerRowCount = 5;
int yPos = 0;
for(int i=0;i<ovalShape.Count;i++)
{
if(i % shapesPerRowCount == 0) //reach end of the row, so offset Y position by Height
yPos += shapeHeight;
int xPos = i*shapeWidth;
DrawShapeAtPos(ovalShape[i], xPos, yPos); //some special function that draws the shape
}
A very generic code, but just to provide you an idea.
If it's not what you're searching for, please clarify.

Categories