Index is outside the bound of the array [duplicate] - c#

This question already has answers here:
What is an IndexOutOfRangeException / ArgumentOutOfRangeException and how do I fix it?
(5 answers)
Closed 5 years ago.
At First I don't know which one is outside the size. And as you can see I have put % not to be outside the array. This is my code, please don't blame me for any childish mistake. If you have tips for a more efficient encrypting method I am opened
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using System.Text;
namespace encrypting
{
public partial class Form1 : Form
{
string text;
string key;
public string calcXor(string a, string b)
{
char[] charAArray = a.ToCharArray();
char[] charBArray = b.ToCharArray();
char[] result = new char[6];
int len = 0;
for (int i = 0; i < a.Length; i++)
{
if (i != 0)
result[i] = (char) ( ((int)charAArray[a.Length % i] ^ (int)charBArray[b.Length % i]) ) ; //error
}
return new string(result);
}
private void Crypt()
{
char[] a;
int i, sizeoftext = text.Length,j=0;
string somestring ="";
string key = textBox2.Text;
StringBuilder sb = new StringBuilder(somestring);
for(i=0;i<sizeoftext-1;i++)
{
if (i == key.Length-1)
j = 0;
}
somestring = calcXor(text, key);
if (File.Exists(textBox3.Text)) ;
File.Create(textBox3.Text).Close();
System.IO.File.WriteAllText(textBox3.Text, somestring);
}
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void label1_Click(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
text = File.ReadAllText(textBox1.Text);
Crypt();
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
key = this.Text;
}
private void button2_Click(object sender, EventArgs e)
{
OpenFileDialog fd = new OpenFileDialog();
if (fd.ShowDialog() == DialogResult.OK)
{
textBox1.Text = fd.FileName;
}
}
private void textBox2_TextChanged(object sender, EventArgs e)
{
}
private void label2_Click(object sender, EventArgs e)
{
}
private void button3_Click(object sender, EventArgs e)
{
FolderBrowserDialog fd = new FolderBrowserDialog();
if(fd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
textBox3.Text = fd.SelectedPath;
textBox3.Text = textBox3.Text +"\\" + textBox4.Text + ".txt";
}
}
private void textBox4_TextChanged(object sender, EventArgs e)
{
}
private void textBox3_TextChanged(object sender, EventArgs e)
{
}
}
}
Please help me.

If your strings are longer than 6 characters the following assignment will be out of bounds:
result[i] = (char) ( ((int)charAArray[a.Length % i] ^ (int)charBArray[b.Length % i]) ) ; //error

Related

Incorrect calculation output

I am trying to create a simple form for calculating speed, distance and time traveled, but the calculations come out wrong.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace _2ndTask
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
double speed, time, distance, laiks, garums, atrums; // laiks = time2, garums = distance2, atrums = speed2
private void label1_Click_1(object sender, EventArgs e)
{
}
private void textBox3_TextChanged(object sender, EventArgs e)
{
bool timeInput = double.TryParse(textBox3.Text, out laiks);
if (!timeInput || laiks < 0 || laiks > 9999)
{
// MessageBox.Show("Ignorēt šo paziņojumu.");
}
// timeInput = float.Parse (textBox3.Text);
}
private void textBox2_TextChanged2(object sender, EventArgs e)
{
bool cGarumsInput = double.TryParse(textBox2.Text, out garums);
if (!cGarumsInput || garums < 0 || garums > 999999)
{
// MessageBox.Show("Ignorēt šo paziņojumu.");
}
}
private void textBox1_TextChanged_1(object sender, EventArgs e)
{
bool speedInput = double.TryParse(textBox3.Text, out atrums);
if (!speedInput || atrums < 0 || atrums > 9999)
{
// MessageBox.Show("Ignorēt šo paziņojumu.");
}
}
private void button2_Click(object sender, EventArgs e)
{
time = (garums / atrums);
label4.Text = time.ToString();
}
private void panel1_Paint(object sender, PaintEventArgs e)
{
}
private void button3_Click(object sender, EventArgs e)
{
distance = atrums * laiks;
label4.Text = distance.ToString() + " Km.";
}
private void button1_Click(object sender, EventArgs e)
{
speed = garums / laiks;
label4.Text = speed.ToString() + " Km/h.";
}
}
}
Before I added TryParse the calculations were correct, but the forms would crash whenever values would be deleted from textboxes.
It should output 140 underneath (multiply time and speed) instead it outputs 49. Inputting other numbers also gives wrong result
You have a typo. You are assigning the text from textBox3 to both atrums and laiks. Presumably one of them should use the text from textBox1.

Why when looping in timer tick event over images list it's throwing exception parameter is not valid?

System.ArgumentException: 'Parameter is not valid.'
private void timer1_Tick(object sender, EventArgs e)
{
for (int i = 0; i < myGifList.Count; i++)
{
Bitmap bmp = new Bitmap(myGifList[i]);
pictureBox1.Image = bmp;
bmp.Dispose();
}
}
After the loop end it's throwing the exception.
Before that I did :
private void timer1_Tick(object sender, EventArgs e)
{
for (int i = 0; i < myGifList.Count; i++)
{
pictureBox1.Image = new Bitmap(myGifList[i]);
}
}
But then it's throwing out of memory exception.
And before all that the first time I tried this :
int counter = 0;
private void timer1_Tick(object sender, EventArgs e)
{
if(counter == 10)
{
counter = 0;
}
for (int i = 0; i < myGifList.Count; i++)
{
Bitmap bmp = new Bitmap(myGifList[counter]);
pictureBox1.Image = bmp;
}
counter++;
}
This is working the images are looping in the pictureBox1 but after some time it's throwing the out of memory exception.
The full code :
I'm downloading images then reading the images back to a List then trying to display them in a picutreBox1 and using trackBar1 to change the looping speed of the images in the pictureBox1 with a timer.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Extract
{
public partial class Form1 : Form
{
List<string> myGifList = new List<string>();
public Form1()
{
List<string> times = new List<string>();
string t = "";
InitializeComponent();
using (WebClient client = new WebClient()) // WebClient class inherits IDisposable
{
client.Headers.Add("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.61 Safari/537.36");
client.DownloadFile("https://myimages/", #"D:\localfile.html");
var file = File.ReadAllText(#"D:\localfile.html");
int idx = file.IndexOf("arrayImageTimes.push");
int idx1 = file.IndexOf("</script>", idx);
string results = file.Substring(idx, idx1 - idx);
var statements = results.Split(new string[] { ";" }, StringSplitOptions.RemoveEmptyEntries);
for (int i = 0; i < statements.Length; i++)
{
if (i == 10)
{
break;
}
string number = statements[i].Split('\'')[1];
times.Add(number); // add to a list instead
var link = "https://myimages" + number;
client.DownloadFile(link, #"D:\Images\Image" + i + ".jpeg");
}
}
FileInfo[] fi;
DirectoryInfo dir1 = new DirectoryInfo(#"D:\Images");
fi = dir1.GetFiles("*.jpeg");
for (int i = 0; i < fi.Length; i++)
{
myGifList.Add(fi[i].FullName);
}
}
private void Form1_Load(object sender, EventArgs e)
{
}
int counter = 0;
private void timer1_Tick(object sender, EventArgs e)
{
if(counter == 10)
{
counter = 0;
}
for (int i = 0; i < myGifList.Count; i++)
{
Bitmap bmp = new Bitmap(myGifList[counter]);
pictureBox1.Image = bmp;
}
counter++;
}
private void button1_Click(object sender, EventArgs e)
{
timer1.Enabled = true;
}
private void trackBar1_Scroll(object sender, EventArgs e)
{
timer1.Interval = 100 * trackBar1.Value;
}
}
}
You seem like you're trying to loop over myGifList, but then you've hardcoded a value of 10 in the method.
However, the bigger issue is that you're not even using i defined by the loop, so you're just overriding the same Bitmap myGifList.Count times, for nothing - making your code inefficient.
Try:
private void timer1_Tick(object sender, EventArgs e)
{
if (counter == myGifList.Count)
counter = 0;
pictureBox1.Image?.Dispose();
Bitmap bmp = new Bitmap(myGifList[counter]);
pictureBox1.Image = bmp;
counter++;
}
Note that you should use the null conditional operator ? to prevent a possible NullReferenceException when calling .Dispose():
pictureBox1.Image?.Dispose();
This would happen on the first time setting the image as pictureBox1.Image would be null, causing .Dispose() to throw an exception.
Even better would be to use the PictureBox.ImageLocation property which would allow you to display the image without creating a Bitmap object every time:
private void timer1_Tick(object sender, EventArgs e)
{
if (counter == myGifList?.Count)
counter = 0;
pictureBox1.ImageLocation = myGifList[counter];
counter++;
}
Sidenote: the Timer.Interval property is also in milliseconds, so I'd bump up the 100 value you have in trackBar1_Scroll(...) if you want to actually be able to see the images looping.

How to set value to textbox in c# from jagged array?

In the picture I want the save button to save the entries of customers to a jagged array and then when I press the show button the saved names should show into the text box below.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace week5hw
{
public partial class Form1 : Form
{
string[][] str = new string[3][];
public Form1()
{
InitializeComponent();
}
public void Button1_Click(object sender, EventArgs e)
{
String names = textBox1.Text;
str[0] = new string[5];
str[0][0] = names;
}
private void Button2_Click(object sender, EventArgs e)
{
}
}
}
I still don't see how a jagged array applies here. You need to give more details about how the program is supposed to work.
At any rate, you need to declare an int variable to track how many of those spots have been used. That variable can also be used to determine which "row" in your jagged array to store the entered name in.
Might look something like this:
public partial class Form1 : Form
{
int count=0;
string[][] str = new string[3][];
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
label1.Text = "The number of free space in room is: " + str.Length;
textBox2.Multiline = true;
}
private void button1_Click(object sender, EventArgs e)
{
if (textBox1.Text.Trim().Length > 0)
{
if (count < str.Length)
{
str[count] = new string[] { textBox1.Text };
count++;
label1.Text = "The number of free space in room is: " + (str.Length - count);
textBox1.Clear();
textBox1.Focus();
}
else
{
MessageBox.Show("No space left!");
}
}
}
private void button2_Click(object sender, EventArgs e)
{
textBox2.Clear();
for(int i=0; i<count; i++)
{
textBox2.AppendText(str[i][0] + "\r\n");
}
}
}

Refreshing a chart control

This one is driving me a bit crazy. Any help gratefully received. It's a simple program to receive temperature data from an Arduino based temp sensor, and display it in a graph control on a form. The program works fine, and parses the temp data frame a treat. However..... the graph object doesn't refresh, and the whole point is to show the data over time. I thought that the chart1.DataBind command that I put in forced a refresh. I am using Visual Studio 2013 Express. Any thoughts as to what I am doing wrong very much appreciated.
// Start of program.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace serial_port_with_events_attempt_4
{
public partial class Form1 : Form
{
string RxString;
int RxRead;
int i;
int RxDec1;
int RxDec2;
int RxDec3;
float RxFloat;
float RxFloat2;
string locnString;
public Form1()
{
InitializeComponent();
}
private void buttonStart_Click(object sender, EventArgs e)
{
serialPort1.PortName = "COM8";
serialPort1.BaudRate = 9600;
serialPort1.Open();
if (serialPort1.IsOpen)
{
buttonStart.Enabled = false;
buttonStop.Enabled = true;
textBox1.ReadOnly = false;
}
}
private void buttonStop_Click(object sender, EventArgs e)
{
if (serialPort1.IsOpen)
{
serialPort1.Close();
buttonStart.Enabled = true;
buttonStop.Enabled = false;
textBox1.ReadOnly = true;
}
}
private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
RxRead = serialPort1.ReadByte();
this.Invoke(new EventHandler(DisplayText));
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
}
private void DisplayText(object sender, EventArgs e)
{
if (RxRead == 126)
{
textBox1.AppendText(Environment.NewLine);
i = 0;
}
if (i< 23)
{
if (i == 7)
{
if (RxRead == 51) // 51 in this position means that the temp sensor is the one in the wooden box
{
textBox1.AppendText("Temperature in Nick's office = ");
locnString = ("Nick's office");
}
}
if (i == 17)
{
RxDec1 = RxRead - 48; // Read the tens unit
}
if (i == 18)
{
RxDec2 = RxRead - 48; // Read the units
}
if (i == 20)
{
RxDec3 = RxRead - 49; // read the decimal
}
if (i == 22)
{
RxFloat = ((RxDec1 * 10) + RxDec2);
RxFloat2 = RxDec3;
RxFloat2 = RxFloat2 / 10;
RxFloat = RxFloat + RxFloat2;
RxString = RxFloat.ToString();
if (RxFloat < 30 && RxFloat >20)
{
// Put the value in the main text box if it is not corrupt, (checking if the range is reasonable
textBox1.AppendText(RxString); // Frig about to get the reads in the right format and added together
// Add a new line into the temperature database
temperature1DataSetTableAdapters.Temp1TableAdapter temp1tableadapter = new temperature1DataSetTableAdapters.Temp1TableAdapter();
temp1tableadapter.Insert(DateTime.Now, RxFloat, locnString);
}
// Delete any old data.
temperature1DataSetTableAdapters.TempTableAdapter temp2tableadapter = new temperature1DataSetTableAdapters.TempTableAdapter();
temp2tableadapter.DeleteTempQuery();
// The above two lines work, but I need to amend to select on date TODO
chart1.DataBind();
}
}
i=i+1;
}
private void Form1_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'temperature1DataSet.Temp' table. You can move, or remove it, as needed.
this.tempTableAdapter.Fill(this.temperature1DataSet.Temp);
}
}
}
Cheers,
Nick James

C# Hangman Game Error

I keep having this error.
ArgumentOutOfRangeException was unhandled.
Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index
Below is the complete code of the form that has the problem and it is where the Hangman game takes place.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace Hangman_APPD_Assignment
{
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
The List labels = new List(); is the label that the makeLabels() method is going to use it.
String w = "";
List<Label> labels = new List<Label>();
int score = 0, missed = 0, correctCount = 0, gameCount = 1;
The code below is when the user clicks the QUIT button, the application will close.
private void btnQuit_Click(object sender, EventArgs e)
{
Application.Exit();
}
The code below is when the form loads or shows up, the makeLabels() method is used.
private void Form2_Load(object sender, EventArgs e)
{
makeLabels();
}
The code below is to use the random word and convert in to a string replacing each alphabet with a symbol '_'. The converted string will be put inside a label called Labels.
private void makeLabels()
{
w = getRandomWord().ToLower();
w.Replace(" ", "");
char[] letters = w.ToCharArray();
int space = 569 / letters.Length - 1;
for (int i = 0; i < letters.Length; i++)
{
labels.Add(new Label());
labels[i].Location = new Point((i * space) + 10, 109);
labels[i].Parent = groupBox2;
labels[i].Text = "_" + i;
labels[i].BringToFront();
labels[i].CreateControl();
}
lblLength.Text = letters.Length.ToString();
}
The code below is a method to create a new game when 1) the user guesses the word completely or 2) the user runs out of guesses.
private void newGame()
{
gameCount++;
if (gameCount == 15)
{
this.Hide();
if (score >= 7)
{
Form4 f4 = new Form4();
f4.ShowDialog();
}
else
{
Form6 f6 = new Form6();
f6.ShowDialog();
}
}
else
{
getRandomWord();
makeLabels();
enableLetterButtons();
lblMissed.Text = "";
hangPic.Image = Hangman_APPD_Assignment.Properties.Resources.part0;
}
}
The code below gets a random word from the string array to be used as the mystery word in the game.
public string getRandomWord()
{
Random randomNum = new Random();
String[] words = {"virus", "network", "syntax", "router", "switch", "worms", "trojan", "email", "bios",
"cmos", "ram", "cipher", "malware", "botnet", "cookies", "patches", "cryptograph",
"metamorphic", "polymorphic", "rootkit", "logicbomb", "spam", "spyware", "keyloggers",
"adware", "software", "hardware", "botherder", "phishing", "whaling", "pharming",
"vishing", "spim", "topology", "tailgating", "loop", "java", "motherboard", "unique",
"parameter"};
int randomNumber = randomNum.Next(0, (words.Length - 1));
return words[randomNumber];
}
The code below is to change the picture every time the user guesses wrongly.
private void setPicture(int wrongTry)
{
switch(wrongTry)
{
case 0:
hangPic.Image = Hangman_APPD_Assignment.Properties.Resources.part0;
break;
case 1:
hangPic.Image = Hangman_APPD_Assignment.Properties.Resources.part1;
break;
case 2:
hangPic.Image = Hangman_APPD_Assignment.Properties.Resources.part2;
break;
case 3:
hangPic.Image = Hangman_APPD_Assignment.Properties.Resources.part3;
break;
case 4:
hangPic.Image = Hangman_APPD_Assignment.Properties.Resources.part4;
break;
case 5:
hangPic.Image = Hangman_APPD_Assignment.Properties.Resources.part5;
break;
case 6:
hangPic.Image = Hangman_APPD_Assignment.Properties.Resources.part6;
break;
}
}
The code below is to call a method when the user clicks one of the alphabet buttons.
private void checkGuessedLetter(string wordToGuess, string guessedLetter, Button buttonName)
{
int strLength = wordToGuess.Length;
char letter = guessedLetter.ToCharArray()[0];
buttonName.Enabled = false;
if (w.Contains(guessedLetter))
{
char[] LS = w.ToCharArray();
for (int i = 0; i < LS.Length; i++)
{
if (LS[i] == letter)
{
MessageBox.Show("The value of w is " + w + " AND " + i);
labels[i].Text = letter.ToString();
conditionPic.Image = Hangman_APPD_Assignment.Properties.Resources.correctpic;
correctCount++;
MessageBox.Show("You got correct " + correctCount + " time(s).");
if (correctCount == strLength)
{
MessageBox.Show("Good job! Keep it up, matey!", "Victory!", MessageBoxButtons.OK, MessageBoxIcon.None);
score++;
lblScore.Text = score.ToString();
newGame();
missed = 0;
correctCount = 0;
labels.Clear();
}
}
foreach (Label l in labels)
if (l.Text == "__") return;
}
}
else
{
conditionPic.Image = Hangman_APPD_Assignment.Properties.Resources.wrong;
lblMissed.Text += " " + letter.ToString() + " |";
missed++;
MessageBox.Show("You missed " + missed + " time(s).");
setPicture(missed);
if (missed == 6)
{
MessageBox.Show("Unfortunately, you lost this round... Make sure you won't let this happen again, "
+ "or else you will end up in Davy Jones' Locker.", "Defeat!", MessageBoxButtons.OK,
MessageBoxIcon.Error);
newGame();
missed = 0;
correctCount = 0;
labels.Clear();
}
}
}
The code below is to get the score that is accumulated at the lblScore label to be shown in the next form.
public int getScore()
{
int score = int.Parse(lblScore.Text);
return score;
}
The codes below is to call a method when the user clicks a button that contains an alphabet to guess the word in the Hangman game.
private void Abtn_Click(object sender, EventArgs e)
{
checkGuessedLetter(w, "a", Abtn);
}
private void Bbtn_Click(object sender, EventArgs e)
{
checkGuessedLetter(w, "b", Bbtn);
}
private void Cbtn_Click(object sender, EventArgs e)
{
checkGuessedLetter(w, "c", Cbtn);
}
private void Dbtn_Click(object sender, EventArgs e)
{
checkGuessedLetter(w, "d", Dbtn);
}
private void Ebtn_Click(object sender, EventArgs e)
{
checkGuessedLetter(w, "e", Ebtn);
}
private void Fbtn_Click(object sender, EventArgs e)
{
checkGuessedLetter(w, "f", Fbtn);
}
private void Gbtn_Click(object sender, EventArgs e)
{
checkGuessedLetter(w, "g", Gbtn);
}
private void Hbtn_Click(object sender, EventArgs e)
{
checkGuessedLetter(w, "h", Hbtn);
}
private void Ibtn_Click(object sender, EventArgs e)
{
checkGuessedLetter(w, "i", Ibtn);
}
private void Jbtn_Click(object sender, EventArgs e)
{
checkGuessedLetter(w, "j", Jbtn);
}
private void Kbtn_Click(object sender, EventArgs e)
{
checkGuessedLetter(w, "k", Kbtn);
}
private void Lbtn_Click(object sender, EventArgs e)
{
checkGuessedLetter(w, "l", Lbtn);
}
private void Mbtn_Click(object sender, EventArgs e)
{
checkGuessedLetter(w, "m", Mbtn);
}
private void Nbtn_Click(object sender, EventArgs e)
{
checkGuessedLetter(w, "n", Nbtn);
}
private void Obtn_Click(object sender, EventArgs e)
{
checkGuessedLetter(w, "o", Obtn);
}
private void Pbtn_Click(object sender, EventArgs e)
{
checkGuessedLetter(w, "p", Pbtn);
}
private void Qbtn_Click(object sender, EventArgs e)
{
checkGuessedLetter(w, "q", Qbtn);
}
private void Rbtn_Click(object sender, EventArgs e)
{
checkGuessedLetter(w, "r", Rbtn);
}
private void Sbtn_Click(object sender, EventArgs e)
{
checkGuessedLetter(w, "s", Sbtn);
}
private void Tbtn_Click(object sender, EventArgs e)
{
checkGuessedLetter(w, "t", Tbtn);
}
private void Ubtn_Click(object sender, EventArgs e)
{
checkGuessedLetter(w, "u", Ubtn);
}
private void Vbtn_Click(object sender, EventArgs e)
{
checkGuessedLetter(w, "v", Vbtn);
}
private void Wbtn_Click(object sender, EventArgs e)
{
checkGuessedLetter(w, "w", Wbtn);
}
private void Xbtn_Click(object sender, EventArgs e)
{
checkGuessedLetter(w, "x", Xbtn);
}
private void Ybtn_Click(object sender, EventArgs e)
{
checkGuessedLetter(w, "y", Ybtn);
}
private void Zbtn_Click(object sender, EventArgs e)
{
checkGuessedLetter(w, "z", Zbtn);
}
The code below is to enable back all the buttons that has been clicked on the previous game.
private void enableLetterButtons()
{
Abtn.Enabled = true;
Bbtn.Enabled = true;
Cbtn.Enabled = true;
Dbtn.Enabled = true;
Ebtn.Enabled = true;
Fbtn.Enabled = true;
Gbtn.Enabled = true;
Hbtn.Enabled = true;
Ibtn.Enabled = true;
Jbtn.Enabled = true;
Kbtn.Enabled = true;
Lbtn.Enabled = true;
Mbtn.Enabled = true;
Nbtn.Enabled = true;
Obtn.Enabled = true;
Pbtn.Enabled = true;
Qbtn.Enabled = true;
Rbtn.Enabled = true;
Sbtn.Enabled = true;
Tbtn.Enabled = true;
Ubtn.Enabled = true;
Vbtn.Enabled = true;
Wbtn.Enabled = true;
Xbtn.Enabled = true;
Ybtn.Enabled = true;
Zbtn.Enabled = true;
}
The code below is to close the application when the user clicked the X button on the top right-hand corner of the application.
private void btnOut_Click(object sender, EventArgs e)
{
Application.Exit();
}
}
}
P.S. I'm sorry I forgot to put in where the error comes from.
So the error is at the
labels[i].Text = letter.ToString();
in the checkGuessedLetter(string wordToGuess, string guessedLetter, Button buttonName) method.
The problem is in these lines:
newGame();
missed = 0;
correctCount = 0;
labels.Clear();
The key thing is to stop and think about what newGame does and then think about what you do afterwards? Since this is homework (I assume from some of the names) really go and think about it.
Done? Good. So hopefully you realised that your newGame method calls MakeLabels to generate the labels and that you then a couple of lines later clear out labels. This means that for subsequent games your labels list will always be empty.
The correct fix for this is that the last three lines I quoted are all part of creating a new game so should be in that method. And indeed you only need to clear the labels when you make new ones so make that part of that method too. Do this and your program will be clearer and hopefully work too! :)

Categories

Resources