Simple C# direction with declaring variables - c#

I just started trying to learn C#. I've read probably 50 tutorials so far and thought I had a good understanding. Apparently I was wrong. I've been doing a lot of reading on msdn.microsoft.com's C# Programmer's Reference but it's seeming to not be the best source for tutorials.
I'm literally trying to accomplish the most simplest of tasks. Trying to understand variables, manipulation, and inputs. I come from web programming and want to turn a PHP script into a desktop application so I'm trying to learn the basics of C# and I think I might need to learn a different language instead.
Basically, I have a textbox and a button. When the button is clicked, I want to check the text in the textbox and see if it matches a certain string. Then display a message box with a message.
private void btnClick_Click(object sender, EventArgs e) {
if(txtCL.Text == "one") {
bool myTest = true;
} else {
bool myTest = false;
}
if(myTest == true) {
MessageBox.Show("You entered the correct password.", "Important Message");
} else {
MessageBox.Show("The password you entered is not correct.", "Incorrect Input");
}
}
Would really appreciate if someone could point me to better tutorials so I can learn quicker. Microsoft's documentation really hasn't taught me anything really.
I apologize for the stupid question, feel free to call me an idiot.

It's a scoping issue, myTest does not exist, at least not down there - you're creating it each time within the scope of each of your initial conditions. If you do:
bool myTest = false;
if(txtCL.Text == "one") {
myTest = true;
}
if(myTest == true) {
MessageBox.Show("You entered the correct password.", "Important Message");
} else {
MessageBox.Show("The password you entered is not correct.", "Incorrect Input");
}
Then you're specifying your boolean value, and setting it to false (which is the default value for a bool anyway, actually), then checking if your condition is met and reassigning it accordingly; it can then be evaluated to show your message box.
You could shorten this code yet more, an exercise for the reader. (:

you don't really need a bool variable, you can make it simplier:
private void btnClick_Click(object sender, EventArgs e)
{
if(txtCL.Text == "one")
{
MessageBox.Show("You entered the correct password.", "Important Message");
}
else
{
MessageBox.Show("The password you entered is not correct.", "Incorrect Input");
}
}
and if you need some tutorials, just google "C# beginner tutorials" or if you prefer video tutorials, you can take a look here.

if(...) {
bool myTest = true;
} else {
bool myTest = false;
}
// At this point in time 'myTest' is not a known variable.
// It's out of scope already s your next line will cause a compile error.
if(myTest == true) {
...
}
So you need to declare the variable in scope
bool myTest = false;
if(...) {
myTest = true;
}
// Now you can use the myTest variable
if(myTest) {
...
}
As you already pointed out, you don't need the variable at all, since this would work all the same
private void btnClick_Click(object sender, EventArgs e) {
if(txtCL.Text == "one") {
MessageBox.Show("You entered the correct password.", "Important Message");
} else {
MessageBox.Show("The password you entered is not correct.", "Incorrect Input");
}
}
You can read as many books as you like, but since you already have programming experience with PHP I'd suggest to get more hands on experience with C#. In parallel a book of course does not hurt. But I think the approach you are following (reading online, coding stuff) will pay off in the end. Give it some time. Practice. A lot.

i am assuming that nothing is happening when you click the button. is this true? if it is, put a break point at the line: if(txtCL.Text == "one") , run the app and click it. If you do not hit the break point then there is no linkage between the 'click' event and your code. Explore the button properties and you will see a way to make the linkage.
stick with it, i was a PHP guy and now a C# guy. It can be done.

Related

C# How do I make my loop not loop back to the first line?

I have been working on a text adventure for a while, but I am having an issue. I have a tutorial, but I want to know how when the user types something that isn't listed, instead of asking the question again, just displaying the option. My example here is a tutorial option that isn't available yet, so they have to type back. I want it so if they type anything other then back, it just displays [Back] and not "That option isn't listed.". In the code example I have tried to use more than one static void because maybe I couldn't reference my own void but that wouldn't work, And I separated the writing and the back option into two but it still doesn't work. When the code example has SW(60, "text") that is just a custom thing for slow write and the 60 is 60 millisecond delay. So, whenever I run it, and type something other then back it will say "That option isn't listed.", like planed but then somehow clear the line and tell you the settings are disabled.
Here is my code.
'''
static string TutorialBack;
public static void TutorialLine()
{
Console.Clear();
SW(40, "The tutorial is currently being devolped, thank you for your patience and support.");
Game.TutorialOof();
}
public static void TutorialOof()
{
Game.Tutorial();
}
static void Tutorial()
{
Thread.Sleep(1600);
Console.WriteLine();
SW(40, "[Back]");
Console.WriteLine();
TutorialBack = Console.ReadLine();
if (string.Equals(TutorialBack, "back", StringComparison.CurrentCultureIgnoreCase))
{
Console.Clear();
Game.Menue();
}
else
{
SW(60, "That option isn't listed.");
Game.TutorialOof();
}
Thanks for any help.
Text adventures are still alive? ;)
I think you should use the var to check equals not the type (string).
// ...
if (TutorialBack.Equals("Back", StringComparison.CurrentCultureIgnoreCase))
{
Console.Clear();
Game.Menue();
}
// ...
Edit: Sorry if I misunderstood what you mean. If you want keep the current just quote out the instruction inside else.
else
{
//SW(60, "That option isn't listed.");
//Game.TutorialOof();
}
Or
else
{
//SW(60, "That option isn't listed.");
Game.TutorialOof();
}

C# backspace on textbox creating errors immediately

I am creating an event where if someone types into a text box it will show an error using this code:
try
{
dblCostSqFt = double.Parse(txtCost.Text);
}
catch
{
MessageBox.Show("Error. You must enter valid numbers. Please correct.");
txtCost.Select();
return;
}
The issue with this is if I input a backspace it will throw that error message immediately I would like to make it to where that doesn't happen.
You're working with userinput here. Therefore i'd suggest to use Double.TryParse()
If you've got a string, and you expect it to always be a double (say, if some web service is handing you a double in string format), you'd use Double.Parse().
If you're collecting input from a user, you'd generally use Double.TryParse(), since it allows you more fine-grained control over the situation when the user enters invalid input.
With tryparse() your code will be something like this:
if (!double.TryParse(txtCost.Text, out var dblCostSqFt))
{
MessageBox.Show("Error. You must enter valid numbers. Please correct.");
txtExample.Select(0, txtCost.Text.Length);
return;
}
To make the example complete and address the issue one could simply check if the Text is not null or empty by using String.IsNullOrEmpty() making the whole code:
// makes sure your app isn't crashing upon backspaces.
if(string.IsNullOrEmpty(textCost.Text))
{
// Personally i'd indicate the user nothing is typed in (yet).
return;
}
if (!double.TryParse(txtCost.Text, out var dblCostSqFt))
{
// The user filled in something that can't be parse to doubles.
MessageBox.Show("Error. You must enter valid numbers. Please correct.");
txtExample.Select(0, txtCost.Text.Length);
return;
}
// All is great; Do stuff with dblCostSqFt.
Assuming you are using WPF for your UI without straying too far from what you have I would use something like below (as LarsTech suggested, use TryParse to test if the value can be converted). Note the if block surrounding the core code within the function, you can avoid execution entering the if block by checking if the key pressed was backspace. I also added a check for the enter key as many users would press the enter key to close the MessageBox, which would cause the event to trigger once again.
private void txtExample_KeyUp(object sender, KeyEventArgs e)
{
if (e.Key != Key.Back && e.Key != Key.Enter)
{
double dblCostSqFt = 0;
if (!double.TryParse(txtExample.Text, out dblCostSqFt))
{
MessageBox.Show("Error. You must enter valid numbers. Please correct.");
txtExample.Select(0, txtExample.Text.Length);
}
}
}
Never rely on exception handling to control the workflow of your application, exceptions have a ton of overhead and it is typically a bad practice in general.
You can accomplish the same thing in WinForms as well using the following...
private void txtExample_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode != Keys.Back && e.KeyCode != Keys.Enter)
{
double dblCostSqFt = 0;
if (!double.TryParse(txtExample.Text, out dblCostSqFt))
{
MessageBox.Show("Error. You must enter valid numbers. Please correct.");
txtExample.Select();
}
}
}
It looks like you are using WinForms because your textbox.Select function call does not supply any arguments, only WinForms supports an overload of the select function without any arguments.

Execute specific blocks of code based on which key on the keyboard is pressed

I am very new to the programming world and recently dove into c#. I don't want to waste your time so I'll get right to it. I wanted to create a program just to test my knowledge, and thought I could attempt to execute specific blocks of code based on which key on the keyboard is pressed by the user. I tried doing this by creating an event handler that contained if statements, but then realized I didn't know how to have the event handler active in the program.
For example, and as you can see in the below snippet, after the WriteLine in Line 5 lets say I wanted to raise the EventKeyPress event so that it waits for user input and reads the key they have pressed and reacts accordingly, how would I do that?
Again, I'm almost a complete beginner and have searched around for explanations about event handlers for hours and still can't wrap my head around what I am supposed to do or if I am even using the event handler correctly. Thanks in advance!
static void Main();
{
if (search == "Ball")
{
Console.WriteLine("Press enter to exit or backspace to return to the search bar")
// RIGHT HERE
}
else
{
Console.WriteLine("Sorry, I don't recognize {0}", search);
}
void EventKeyPress(object sender, KeyPressEventArgs e)
{
for (int i = 0; i < 1;)
{
if (e.KeyChar == (char)Keys.Enter)
{
// exit app
}
else if (e.KeyChar == (char)Keys.Back)
{
// go back to search
}
else
{
i = 0; // error
}
}
}
}
So, you're asking for something that involves Threading which is not a beginner thing to accomplish at all. The best way to do this for a beginner is to ask for a prompt, then accept as an input. For example.
Console.WriteLine("Hello, what's your name?");
string nameStr = Console.ReadLine();
Console.WriteLine($"Hello, {nameStr}");
You can then use your variable and apply it to an if/while or whatever kind of conditional.
if (nameStr == "Matt"){
//Do This Code.
}
Once you have that code, add a sequential method that will ask the user to return to the main menu or whatever you want it to do.
Main.ReturnMenu(); //Or whatever you want to use.

How to solve a IndexOutOfRange made by the user?

I'm still new to programming, so every time i get an exeption i try to rewrite code so it is avoided. However in this case i see no way to work around it.
I have a textbox that the user uses to imput commands. The string(imput) is then split after the first space.
private void tbxMainImput_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
string commandText = tbxMainImput.Text.ToLower();
string[] commandTextSplitted = commandText.Split(new char[] { ' ' }, 2, StringSplitOptions.RemoveEmptyEntries);
ReadTextboxImput(commandTextSplitted);
tbxMainImput.ResetText();
e.SuppressKeyPress = true; //anoying beep is removed :)
}
}
this splitted string commandTextSplitted is being used by a switch method ReadTextboxImput
private void ReadTextboxImput(string[] imput)
{
switch (imput[0])
{
//some other cases
case "attack":
StartCombat(imput[1]); //trows exeption if user only types one word
break;
}
}
If a player only types one word, imput[1] doesnt exist, and an IndexOutOfRange exeption is cast(as it should). However the exeption seems unavoidable. the player can type one word and press enter...
so ive been trying some things to check for the exeption and then break out of the code but it doesnt seem to work. The msdn website isn't realy beginners friendly, and all i found on stackoverflow where people asking to find where the error came from. witch i know.
So far i have tried:
case "attack":
if (imput[1] == null) //(imput[1] == system.IndexOutOfRange) doesnt make sense but i had to try
{
rtbOutput.AppendText("Yes yes. Attack nothing...");
break;
}
StartCombat(imput[1]);
break;
i made a method that uses try and catch that worked, but it just detected the error, i wasn't able to do anything with it(like return a false, or something)
Any help would be apreciated.
you can check if the array length is > 1 instead of imput[1] == null
if (imput.Length > 1){
rtbOutput.AppendText("Yes yes. Attack nothing...");
break;
}
StartCombat(imput[1]);
break;

Clearing out a c# form text box

I am making a simple hangman style game in a C# form. I have it set as textBox1_TextChanged. Except everytime the user backspaces their guess letter it takes in blank space. How can I make it so after the message saying right/wrong it clears the space. I am getting annoyed at it telling the user they made a wrong guess after they backspace. This is my first post on this forum so sorry if the code text is weird. I just want the program to clear the text in the textBox after they guess.
UPDATE: Added suggested information. Now it does everything it is supposed to do. Except it pops up a windows saying " was found in the target word". This happens if guessLetter == null || guessLetter == correct || guessLetter == false.
private void textBox1_TextChanged(object sender, EventArgs e)
{
string guessLetter = textBox1.Text;
//textBox1.ReadOnly = true;
if (targetWord == null)
{
MessageBox.Show("Please start a new game.");
textBox1.Text = ("");
}
else
{
if (targetWord.Contains(guessLetter))
{
MessageBox.Show(guessLetter + " was found in the word");
}
else
{
MessageBox.Show(guessLetter + " was not found in the word");
incorrectGuessCtr++;
textBox3.Text = incorrectGuessCtr.ToString();
}
textBox1.Text = ("");
}
}
Don't only check if the targetWord is null, but also the guessLetter. You'd better use string.IsNullOrEmpty too, since it also checks if the string is empty:
if (!string.IsNullOrEmpty(targetWord) && !string.IsNullOrEmpty(guessLetter))
{
...
}
I guess you should also check if there is exactly one letter entered. That would mean this additional check:
if (guessLetter.Length == 1)
{
...
}
You will enter this event when you write code that changes Text property in textbox. I mean this.
textBox3.Text = incorrectGuessCtr.ToString();
Put something in function arguments or set some flags so that you can identify whether the event is called from user input or your clearing the text.
Just check how many times this function is called when user press backspace. You will get the idea.

Categories