I am attempting to pass two values that match (match in hex and binary) and place them into a respective label randomly selected from an array of labels. I am only becoming familiar with the .NET framework (4.0). when I try to debug the program when loading the form an error while debugging "NullReferenceExceptionOccurred" is returned. With additional information stating "Object reference not set to an instance of an object". I've checked but I have not found anything relating to the use of arrays of labels. The error appears to occur on the line binaryLabels[j].Text = qstn;
.
Below is the code in question.
The label arrays are firstly declared
public Random rand = new Random();
public Label[] binaryLabels = new Label[4];
public Label[] hexLabels = new Label[4];
Assigned labels upon form loading
public void frmQstn1_Load(object sender, EventArgs e)
{
binaryLabels[0] = this.lblBinary1;
binaryLabels[1] = this.lblBinary2;
binaryLabels[2] = this.lblBinary3;
binaryLabels[3] = this.lblBinary4;
hexLabels[0] = this.lblHex1;
hexLabels[1] = this.lblHex2;
hexLabels[2] = this.lblHex3;
hexLabels[3] = this.lblHex4;
}
The lines of code below generate the array containing the binary and corresponding hex values.
public void SetUpQuestionBnk()
{
string[] questions = { "0000", "0001", "0010", "0011", "0100", "0101", "0110", "0111", "1000", "1001", "1010", "1011", "1100", "1101", "1110", "1111" };
string[] answers = { "0", "1", "2", "3","4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F" };
int i = rand.Next(0, questions.Length);
string qstn = questions[i];
string ans = answers[i];
int [] lblCount = { 0, 1, 2, 3 };
int j = rand.Next(0, lblCount.Length);
int k = rand.Next(0, lblCount.Length);
binaryLabels[j].Text = qstn;
hexLabels[k].Text = ans;
}
This code should in theory then display the strings "qstn" and "ans" in randomly chosen labels held within arrays "binaryLabels" and "hexLabels" respectively.
The randomisation definitely works when looking at the locals but the error relating to the line binaryLabels[j].Text = qstn;
and presumably hexLabels[k].Text = ans;
If anyone knows how to solve this it would be greatly appreciated.
Edit : **I have checked other "solutions" to this but I have no idea how to apply them to my code as all other solutions do not appear to be working with random values. **