The field 'Form1.answer' is never used - c#

I am getting a random word from a dictionary using:
var word = File.ReadAllLines(#"c:\\CTEMP\\Dictionary2.txt");
and displaying it only partially for the player to guess using:
hintTextBox.Text = GetPartialWord(word[new Random().Next(word.Length)]);
var answer = word[new Random().Next(word.Length)]; // answer = word from dictionary
However I am not able to compare the word the user enters to the word from the dictionary.
I have tried :
private string answer; //assign answer to word from dictionary
private void button2_Click(object sender, EventArgs e)
{
if (answerTextBox.Text == answer)
{MessageBox.Show("You Guessed The Word !");
However I am getting the following warning:
Warning CS0169 The field 'Form1.answer' is never used WindowsFormsApplication2
Any ideas on how I can compare the answer to what is entered in answerTextBox?

The problem is in this line:
var answer = word[new Random().Next(word.Length)];
Here you create new variable instead of using class level one. In if statement you compare value of textbox with class level variable. Also, you get warning because you never assign value to class level variable but compare value of textbox.
That line should be changed to:
this.answer = word[new Random().Next(word.Length)]; //or without "this."

Related

C# Can someone tell me how to fix this? System.ArgumentNullException: 'Value cannot be null. Parameter name: item' [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 months ago.
Improve this question
Code:
namespace DriversLicenceExam
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
LoadKey();
LoadAnswer();
}
private void LoadKey()
{
try
{
const int AnsLgth = 20;
string[] Answers = new string[AnsLgth];
int index = 0;
System.IO.StreamReader inputFile;
inputFile = File.OpenText("DRIVERKEY.txt");
{
Answers[index] = (inputFile.ReadLine());
index++;
}
inputFile.Close();
for (int i = 0; i <= Answers.Length; i++)
{
string value = Answers[i];
listBox1.Items.Add(value);
}
}
catch (Exception)
{
throw;
}
}
I keep getting an error stating 'Value cannot be null. Parameter name; item'
I am relatively new to coding and not sure what this means. Any help or input is appreciated.
The goal of this program is to insert an answer key file, turn it into an array, output it into a listbox, then do the same with answer files, grade the answer files that are submitted by "students" by crossreferencing them with the answer key array, then output the incorrect answers into another listbox.
This is only the first method where I am supposed to input the answer key file then turn it into an array and display it in a listbox.
The answer key text file looks like this:
B
D
A
A
C
A
B
A
C
D
B
C
D
A
D
C
C
B
D
A
You're reading one line from the file into the first element of the array. So the rest of the elements are null. Then you're trying to add all of the elements to a UI control:
listBox1.Items.Add(value);
It's accepting the first non-null value but the remaining 19 null values are problematic.
I suspect you meant for this to be a loop:
{
Answers[index] = (inputFile.ReadLine());
index++;
}
But you forgot... the loop. Perhaps something like this:
var line = "";
while ((line = inputFile.ReadLine()) != null)
{
Answers[index] = line;
index++;
}
Though even then, there's really no guarantee that the number of lines will always equal the hard-coded array size. If there are fewer, the same error will occur. If there are more, a different error will occur.
This is an example where a more dynamic data structure, such as a List<>, would be helpful. Something like this:
var Answers = new List<string>();
Then the collection will automatically grow to only the size needed as you add to it. So the loop would be:
var line = "";
while ((line = inputFile.ReadLine()) != null)
{
Answers.Add(line);
}
Using a List<> is slightly different from using an array. For example, you'd use .Count instead of .Length. But overall what you have is conceptually the same. A List<> is just more dynamic than a fixed-length array.
Here
inputFile = File.OpenText("DRIVERKEY.txt");
{
Answers[index] = (inputFile.ReadLine());
index++;
}
There is no loop around the part that reads a line from the file and assigns it to the array. So only one line is read and only the first entry in the array is filled.
There are further problems further down in the code. But try to understand and fix that one first. Tip: Learn how to work with the debugger. Set breakpoints, step through the code line by line and look at the variables while the code executes.
Here is a good video tutorial on using the debugger in Visual Studio: https://www.youtube.com/watch?v=sACkw915kmg

How can i solve "System.FormatException: 'Input string was not in a correct format.'" problem? [duplicate]

I added a textbox to my form and I'm trying to get the text from it but it comes up with an exception saying
"Input string was not in the correct format."
This is my code:
deleteQuestion = Convert.ToInt32(textBox6.Text);
addQuestion = Convert.ToInt32(textBox7.Text);
listOfQuestions.RemoveAt(deleteQuestion - 1);
foreach (RichTextBox box in boxForQuestions)
{
if (Convert.ToInt32(box.Tag) == deleteQuestion - 1)
{
boxForQuestions.Remove(box);
}
}
In the second part of the code my intention is to delete dynamically added rich text box.
Use Int32.TryParse if you are not in control of what your user types in those textboxes
int deleteQuestion;
if(!Int32.TryParse(textBox6.Text, out deleteQuestion))
{
MessageBox.Show("Not a valid number to delete a question!");
return;
}
int addQuestion;
if(!Int32.TryParse(textBox7.Text, out addQuestion))
{
MessageBox.Show("Not a valid number to add a question!");
return;
}
Of course, the same should be considered for the Tag property used inside the loop but this is set by your code so I presume that it is safe to consider it a valid integer
Another problem in your code is the remove inside the foreach loop. This cannot be done, you cannot change a collection while iterating over it. If you really need to remove an element from that collection you should consider to use a normal for... loop and looping from the last element towards the first one

What is a good way to set a default value in a sorted ComboBox?

When I initialize a combobox with text contents like so, where eo is some object with a ToString() override:
foreach (EncodingInfo ei in Encoding.GetEncodings()) {
Encoding e = ei.GetEncoding();
encodeObject eo = new encodeObject();
eo.Name = ei.DisplayName;
eo.Value = ei.Name;
int targetIndex = this.targetEncodingBox.Items.Add(eo);
}
I can set this to be the default value by using
this.targetEncodingBox.SelectedIndex = targetIndex
However, when the box is actually sorted, and the data initially entered into the box using the Add() method is not sorted, the default index is kept while the box is re-sorted, resulting in an entirely different value being selected almost all of the time.
A basic solution for this is to look up the generated value that the combobox would display and use FindStringExact:
this.targetEncodingBox.SelectedIndex = this.targetEncodingBox.FindStringExact("utf-8 -- Unicode (utf-8)");
However, this results in other problems. The string in question may depend on the user's operating system' language settings in this particular case. This can't be known beforehand.
Thus another way I've found is to manually find the name of the encoding a second time and set the SelectedIndex after the box is fully populated, using the same convention for concatenating the acronym name and translated name as used in the definition for encodeObject.ToString();.
foreach (EncodingInfo ei in Encoding.GetEncodings()) {
if (ei.Name == "utf-8") {
this.sourceEncodingBox.SelectedIndex = this.sourceEncodingBox.FindStringExact(ei.Name + " -- " + ei.DisplayName);
}
}
Note: the definition of the class encodeObject below:
private class encodeObject {
public string Name;
public string Value;
public override string ToString() {
return Value + " -- " + Name;
}
}
This actually works, and does exactly what I want, yet the solution seems quite clunky to do something that should really be a single call. Is there a better way of achieving this?
As Hans commented you need to create that list and store it to a variable.
Since the available encodings are unlikely to change anyway, this should happen in some class constructor or when you load your settings.
This variable then can be re-used anywhere you need it, it also can be easily updated & sorted as you like.
After this step the rest is trivial, create a variable with a default value/index, and once a ComboBox was assigned this list just set the SelectedValue/SelectedIndex value to your default value/index.

Prompt user that input is out of range, based on comparing to sql query

Simply i have a textbox that my users will enter in a Fan rpm.
I need my program to take the entered fanrpm and compare it with a database item called classrpm. My query from the database Will only return 1 item ever.
I need fanrpm to be > classrpm, and if fanrpm >= class rpm a msg box to pop-up and state "Fan RPM exceeds ClassRPM(which is x), please enter a value under ClassRPM.
The code below was my test with fake variable names. I attempted to take and convert the user entered text and the database retrieved item, then using the converted values to do the above if statement, and then output a msg box to inform me if it succeeded.
private void textBox1_TextChanged(object sender, EventArgs e)
{
txfanrpm.MaxLength = 4
string classrpm;
string fanrpm;
using (Fanrpm ds = new Fanrpm(cbdesigntype.SelectedValue.ToString(), cbfansize.SelectedValue.ToString(), cbfanclass.SelectedValue.ToString()))
{
DataTable dt = ds.dataset.Tables[0];
List<string> coolList = new List<string>();
foreach (DataRow row in dt.Rows)
{
coolList.Add(row[0].ToString());
}
classrpm = coolList.ToString();
fanrpm = txfanrpm.Text.ToString();
int classrpmInt;
int fanrpmInt;
classrpmInt = Convert.ToInt32(classrpm);
fanrpmInt = Convert.ToInt32(fanrpm);
if (fanrpmInt >= classrpmInt)
{
MessageBox.Show(this, "user entered fanrpm higher then class rpm which is yadda yadda");
}
else if (fanrpmInt < classrpmInt)
{
MessageBox.Show(this, "Fanrpm is less then Classrpm");
}
}
}
I believe my problem stems in converting my database item into something usable to compare too. Also i think that if my setup works as intended it may tell a user entering 500 at each entry the textbox will refresh and redo the query leading to potential wasted processing power?
-Edit my sql statement works, Though putting the data into a list may be one of my problems.
No way that you could convert a List(Of String) to a single string in that way.
And what if your user types not a number in your textbox?
However, if, as you have said, your DataTable contains always only one row then you could simplify your code to something like this
private void textBox1_TextChanged(object sender, EventArgs e)
{
int classRPM;
int fanRPM;
using (Fanrpm ds = new Fanrpm(....)
{
DataTable dt = ds.dataset.Tables[0];
// Get and convert the value in the field named ClassRPM (assuming is a string)
classRPM = Convert.ToInt32(dt.Rows[0].Field<string>("ClassRPM"));
// Now check if the textbox contains a valid number
if(!Int32.TryParse(txfanrpm.Text, out fanRPM))
{
MessageBox.Show("Not a number....");
return;
}
// Start your logic
if (fanRPM >= classRPM)
{
MessageBox.Show(.....);
}
else if (fanRPM < classRPM)
{
MessageBox.Show(.......);
}
}
}
I think that a TextChanged event is not the proper place for this kind of code. This will trigger everytime your user presses a key and result in a trip to the database for every key press. So if your user wants to type 500 you end asking the db first for "5", then for "50" and finally for "500".
I would prefer to let the user types freely its values and then check when a verify button is pressed or, if this is not possible, to check in the Control.Validating event.
Calling List.ToString() just returns "System.Collections.Generic.List`1[System.String]" rather than any items in the string. (The "ToString()" method is actually inherited from Object, and just returns a string that represents what type of object the object is, except in special cases like StringBuilder.)
I would avoid the TextChanged event because that event will cause your code to execute ever keystroke, which might cause errors when a value is partially entered, or when a user accidentally enters and invalid value and has to backspace.

Displaying a character count while the user is typing?

I'm trying to build a program with that displays the number of characters and words while a user is typing into the text box. I thought I knew what I was doing but ran into this error:
'Cannot implicitly convert type 'string' to
'Systems.Windows.Forms.Label'
This is what I have so far. The last line of code contains the error:
private void userTextBox_TextChanged(object sender, EventArgs e)
{
string userInput = userTextBox.Text;
char charCount;
charCount = userInput[0];
charCountOutput = charCount.ToString();
}
1) You need to set the property on the Label to set the text
charCountOutput.Text = ...
2) The length of a string can be accessed through the Length property
charCountOutput.Text = userInput.Length.ToString();
charCountOutput.Text = charCount.ToString();
Assuming charCountOutput is the label
Your code is trying to assign the Label object the value of a string, which is a type mismatch (obviously).
You're assigning to a textfield, changing the text of the field.
charCountOutput.Text = charCount.ToString();
int countChar = userTextBox.Text.ToString().Length;
Here's a late addition - you probably already have seen this, but here's a really fast approach. Assumes charCountOutput is label on your form:
private void userTextBox_TextChanged(object sender, EventArgs e)
{
var userInput = userTextBox.Text;
charCountOutput.Text = userInput.Length.ToString();
}

Categories

Resources