I am new to C# and after same experience with C++ (year programming in college). Recently we started C# and thing I wanted to do is simple game with printed board (so far I have working only with console applications). I started digging (I will place links to the subjects bellow).
I am using Visual Studio Ultimate 2013. The board I want to make is to be simple board of buttons (but with extra properties). So i created a class that inherits from a button and started adding some stuff (there will be more):
class Field : Button
{
private string owner;
private string temp_owner;
private int level;
private int temp_level;
public Field() : base()
{
owner = "brak";
temp_owner = owner;
level = 0;
temp_level = level;
}
}
Then I looked up how normally buttons are initialized (in Form1.Designer.cs) but Visual Studio wouldn't let me write there anything so I created method build_board and placed it in Form1.cs:
public partial class main_form : Form
{
public main_form()
{
InitializeComponent();
build_board();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private System.Windows.Forms.Button [,] Board;
private void build_board()
{
this.Board = new Field[10, 10];
this.SuspendLayout();
//
// Board
//
for (int i = 0; i < 10; i++)
for (int j = 0; j < 10; j++)
{
this.Board[i, j].BackColor = System.Drawing.SystemColors.Control;
this.Board[i, j].Location = new System.Drawing.Point(10 + i * 10, 10 + j * 10);
this.Board[i, j].Name = "Field [ " + i + " , " + j + " ]";
this.Board[i, j].Size = new System.Drawing.Size(50, 50);
this.Board[i, j].TabIndex = 100 * i + j;
this.Board[i, j].Text = "";
this.Board[i, j].UseVisualStyleBackColor = false;
}
this.ResumeLayout(false);
}
}
Problem is that debugger is screaming about "NullReferenceException was unhandled" in this line:
this.Board[i, j].BackColor = System.Drawing.SystemColors.Control;
I have checked some other topics and they say it may be caused by Board being not initialized but I think I did initialize it. I will appreciate any help and maybe some other tips on how to easy print an array of custom objects.
My research:
C# NullReferenceException was unhandled - Object reference not set to an instance of an object
NullReferenceException was unhandled C#
How to create an array of custom type in C#?
(also many others about printing)
EDIT:
Answer by Pazi01: In the loop there is need to add those two lines:
for (int i = 0; i < 10; i++)
for (int j = 0; j < 10; j++)
{
this.Board[i, j] = new Field();
this.Controls.Add(this.Board[i, j]);
...
}