Unable to pass a parameter in C#? - c#

Okay. For the iLab my class and I are doing this week, we are working with GUIs. The second program we must design is a guessing game. The program is supposed to randomly generate a number, 0 through 100, and pass that number on to be used later. Here is the code I already have.
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;
namespace Guessing_game
{
public partial class Form1 : Form
{
int target();
public Form1()
{
InitializeComponent();
Random r = new Random();
int target = r.Next(0, 100);
}
private void btnEvaluate_Click(object sender, EventArgs e)
{
if (txtGuess.Text == target)
{
}
}
}
}
}
Mind you, the "btnEvaluate_Click" area is not done. This is because the variable "Target" that should be accessible by the program is unable to be read later on.
After reading through some of the comments, I was able to tweak the code so I get one more error: "Field 'Guessing_game.Form1.target' is never assigned to, and will always have its default value 0" IF anyone is going to try and replicate this, I can tell you exactly how to write it. The GUI should have a label, a text box, and a button. The button needs to get the value given to "target" so it can check the user's guess against target's value. I'm using Visual Studio 2010, if it helps.

Try this, You need to declare target public
Random r = new Random();
int target = r.Next(0, 100);
public Form1()
{
InitializeComponent();
}
private void btnEvaluate_Click(object sender, EventArgs e)
{
if (txtGuess.Text == target)
{
}
}

You have to put int target outside of the public Form(). Inside your event, change target to target.ToString().

The parentheses {} define a scope. You've declared the target variable within the scope of the constructor (Form1). Therefore, in order to make it accessible throughout the class, you can make it a class level variable. For example
int target;
public Form1()
{
InitializeComponent();
Random r = new Random();
target = r.Next(0, 100);
}
(Although if you plan to use the Random object again, you'd want to make that a class level variable as well). Also, you're trying to compare an int to a string. It should be
if (txtGuess.Text == target.ToString())
{
}

That's because target is local to the constructor and therefore can't be seen anywhere else. Make target a field in Form1 instead. Because this is homework, I'll let you try that out on your own; let us know if you're still stumped.

Related

Trying to understand C#, WPF and User Input between functions

I am new here as well as to C#. I'm trying to learn it better and as a basic programming challenge for myself, I'm trying to understand how to move or return certain values from user input/text boxes after being submitted to a table that is displayed in a list.
Here is my "challenge" I'm trying to create a simple program that has 2 text boxes one for a name of the new value to a list (not an array I've learned that the hard way) and one for a name of a searched value in a said list. Submit button for each of those text boxes with a message stating either "Value Added" when it was added, or "Found" "Doesn't Exist" for the search button. Then on a side of said boxes and buttons I actually want to display my list with a scrollable 2 column window / box, First column as position in a table like value in which its at and then the actual name of the said value that was added. (Oh an also a clear button for the list itself)
So here is what I've gathered so far. I understand I have to transform all input into a string and then push it to the list. I know how to display the MessageBox.Show("") however I don't know how to code conditions to it. I would try a simple if () but I would first need to be able to program a working search function which requires pushing and pulling data from the list. I know JavaScript has array.push and array.indexof which makes finding and pushing things into an array rather simple, but to my knowledge, C# does not have that function.
I am new to this so any tips on a material to read that would help me learn C# or any tips on how to make this work properly will be appreciated. My biggest struggle is to return a value from the said text box into another private void and using it in my var, in other words pushing the product of a function into another function (like in the example below pushing the Add_Text.Text into the var names = new List<string>(); which is in another void above it. Anyway here is my coding or failed attempt at making this somewhat "work".
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace ArrayApp
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
// ARRAY CODING / LIST CODING
public class Values
{
public string Position { get; set; } = string.Empty;
public string Name { get; set; } = string.Empty;
}
public void App()
{
var names = new List<string>();
}
// BUTTON CLICKS / BUTTON ACTION CODING
private void Add_Button_Click(object sender, RoutedEventArgs e)
{
List_Box.Content = Add_Text.Text;
MessageBox.Show("Value Added");
Add_Text.Clear();
}
private void Search_Button_Click(object sender, RoutedEventArgs e)
{
}
// TEXT BOXES / WHAT BUTTON ACTUALLY INPUTS INTO OUR DISPLAY
private void Add_Text_TextChanged(object sender, TextChangedEventArgs e)
{
}
private void Search_Text_TextChanged(object sender, TextChangedEventArgs e)
{
}
// DISPLAY - List_Box not added yet
}
}
Let's walk through this. As you've already mentioned, you need something to store your data. List is a good idea since you don't know the size.
Currently, you're creating a List of the type string, that would work.
There's actually no need for the Values class because because you can get the index of an item with a function called IndexOf - but later more.
Now, once you show the MessageBox when adding an item, you also have to actually add it to your names list. In order to do so, declare the List in your class and initialize it in your constructor. That way you're able to access if from everywhere in your class.
private List<string> names;
public void MainWindow()
{
InitializeComponent();
names = new List<string>();
}
Adding items can be done with the .Add method, it's pretty straight forward.
private void Add_Button_Click(object sender, RoutedEventArgs e)
{
List_Box.Content = Add_Text.Text;
MessageBox.Show("Value Added");
names.Add(Add_Text.Text); // Adding the content of Add_text.Text
Add_Text.Clear();
}
Searching for an item is pretty easy, too. Just use Contains if you want to know whether the item exists or IndexOf if you want to have the index as well. Note: IndexOf returns -1 if nothing can be found.
private void Search_Button_Click(object sender, RoutedEventArgs e)
{
if(names.Contains( SEARCH_TEXT.TEXT /* or wherever you get your pattern from */ )){
// found, display this in some way
} else {
// not found, display this is some way
}
}
SEARCH_TEXT.TEXT contains the pattern you're looking for. I don't know how you named your control, simply replace it.
That's pretty much it.
So, after doing some reading and also your comments helped a lot, I think I got hang of it and got some basic understanding of C# at least how it works logically. This is the "final" version of the AMAZING program I was trying to create. Thanks for the help everyone!
P.S. The comments are for me to learn and reference in the future when I'm learning C# or forget things :)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
/* QUICK TERMINOLOGY
List = An Array that constantly adjusts its maximum size
names = Our actual "database" or table with our values that we've inputted
List_Box = The display table that is visible on the program itself
var = Variable... You know...
"public" or "private" = Those define whether the function is visible to the rest of the program or other "sheets" in the program
void = Defines whether the return value or the output of a function should be something, void means not specified,
if you want string you put string, if you want an integer you put int... etc etc.
*/
namespace ArrayApp
{
public partial class MainWindow : Window
{
/* Private Function for Creating the List which will be a String
We are using a List instead of an Array as an Array needs
a specific amount of indexes so if we have a specific number of data or
a maximum amount of data that a user can input then array would be used
but since we don't know how many indexes we need a list will automatically
adjust the maximum size of our table to suit our needs. I.e. limitless */
private List<string> names;
public MainWindow()
{
InitializeComponent();
names = new List<string>();
}
/* Class for our Items in our list this is not referring the list above but...
the list that it displays as we have a search on demand
but also allows us to search for specific people in the List (array/table) rather than
display over 100+ people, if our database was to get to that size.
Our class function defines what data can be put into our Display List ( List_Box )
Therefore the index can only be an integer and name can only be a string
more on this later. */
class Items
{
public int Index { get; set; }
public string Name { get; set; }
}
/* The Add Button Function
This button takes the content of the TextBox that is right next to it and
adds it to our list called "names" but does not update our display, instead
it shows us a message stating that the value was added to the list.
If we were using an Array with a limited size, we could use an IF to check
if there is a space available and output a message saying "Full" or "Failed" */
private void Add_Button_Click(object sender, RoutedEventArgs e)
{
names.Add(Add_Text.Text); // Adds the value
Add_Text.Clear(); // Clears the text box
MessageBox.Show("Value Added"); // Displays a message
}
/* Firstly...
* We have an IF function that checks whether "names" contains the content
of the search box, so if its a letter "a", it checks if its in our list.
* It then creates a variable "SearchText" that we can later use that simply
means that instead of writing the whole code we can just refer to it by our new name
* Another variable! This one defines our Index in our list, it takes
our previous variable and looks for it in our list and finds what
the index number of that value is.
* Now, since its Search on demand we essentially have two Lists (arrays) now
that we have the name of the value we looking for in string format,
we also have our index as integer (defined earlier in class). We need to take that data
and add it to our display List and for that we have our function.
Adds new Items to our list using the Items Class and also defines
what data should be put into each column.
* It then clears the search text box
* and shows us that the value has been found.
We then move to ELSE which is simple really...
* Didn't find data
* Clears search text box
* Displays message that its not been found... */
private void Search_Button_Click(object sender, RoutedEventArgs e)
{
if (names.Contains(Search_Text.Text)) // Our If statement
{
var SearchText = Search_Text.Text; // First Variable
var FindIndex = names.IndexOf(SearchText); // Second Variable
List_Box.Items.Add(new Items() { Index = FindIndex, Name = SearchText}); // Adding items to display list
Search_Text.Clear(); // Clear search text box
MessageBox.Show("Data Found"); // Display message
}
else
{
Search_Text.Clear();
MessageBox.Show("Not Found");
};
}
/* Lastly a simple clear button for our display list.
* Once a user searches for many values and wants to clear the display list
* he can do it by hitting a single button.
*
* This button DOES NOT delete anything from our "names" list it only
* clears the display data meaning that the user can search for more data
* that has been added already. */
private void Clear_Button_Click(object sender, RoutedEventArgs e)
{
List_Box.Items.Clear();
}
private void Add_Text_TextChanged(object sender, TextChangedEventArgs e)
{
}
private void Search_Text_TextChanged(object sender, TextChangedEventArgs e)
{
}
private void ListView_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
}
}
}
Here is how it looks, simple but you get the idea, I'm learning...

Greatest Value in a Dataset

I am attempting to find the greatest value in the highlighted column of this access database. I have tried a few ways of doing it but none of them work.
I need to use LINQ. Preferably the from x in y [...] select x; statement. If I cannot to this with the aforementioned then anything using LINQ would probably suffice. If you could explain why your answer works that would help me out a lot.
Edit:
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;
namespace CarStatistics
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'honestRalphsUsedCarsDataSet.tblCars' table. You can move, or remove it, as needed.
this.tblCarsTableAdapter.Fill(this.honestRalphsUsedCarsDataSet.tblCars);
}
private void btnCarAmount_Click(object sender, EventArgs e)
{
lblCarAmount.Text = "Our inventory consists of " + (dgvCars.RowCount - 1).ToString() + " cars!";
lblCarAmount.Visible = true;
}
private void btnMstExpensive_Click(object sender, EventArgs e)
{
//Code to find Max
}
}
}
The appropriate linq method to use would be [Enumerable.Max][1]. There are many overloads but the ones you will want are either the one that works on an IEnumerable<decimal> (assuming that that type of your column is decimal). This would be used as:
source.Select(x=>x.Price).Max()
source would be the IEnumerable that you have the data in and x.Price assumes that the value of that column is obtainable through a property called Price.
The other alternative would be using the overload of max that takes a Func<TSource, decimal> to tell it what data to use for the max:
source.Max(x=>x.Price)
I'm not sure there is much difference apart from in readability. I'd probably be inclined towards the first, particularly since in the first draft of this question I got wrong what the second actually returns (Thanks to Robert McKee for correcting me on that). :)
Something like this should be what you're looking for:
var maxPrice = db.Items.OrderByDescending(i => i.Value).FirstOrDefault().Value;
This works by ordering all of the rows based on the column specified, then takes the first row from that list, and selects the value of that column.

if statements in buttons c#

I'm a brand new n00bie in visual c# and I ran into a weird obstacle that is driving me CRAZY!! Here is the code in question (yes, an Hello World 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 WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
if (textBox1.Text.Equals("Goodbye Cruel World"))
{
textBox1.Text = ("Hello World!");
}
else { textBox1.Text = ("Goodye Cruel World"); }
}
}
}
I also tried to use textBox1.Text=="Goodbye Cruel World"; as the evaluation parameter for the if statement getting no errors in the compiler (by the way I am using Visual Studio 2012 Ultimate)
The program runs fine. I initalised the textbox text property as "Hello World!" using the Design GUI of VS. The problem I am facing is that the code works only the first time the user clicks the button. Any time after the button does NOTHING.
I debugged the code and I made sure that the textbox text property is appropriately changed the first time the user clicks the button. When the user clicks the button a second time (or any time after that for that matter) once the code gets to the if statement it skips it, as if the evaluation of the expression within is FALSE. In fact, keeping up with the debug tool, the button keeps executing only the code within the else block, even though I know for a fact that the TextBox.Text property that I am working with has been appropriately changed before.
What am I missing here??? Why doesn't the button just switches the textbox text value between the two strings I hardcoded within?
You are using three strings, not two. "Goodye Cruel World" is not equal to "Goodbye Cruel World". Hence, you cannot expect any kind of "string swapping" behaviour whatsoever from this source code.
Lesson to learn: Do not use the same string at different points of your code. Instead, create a constant string variable which has that value, and then use it every time you need it. For example code see Habib's answer.
That is a case of defining string constant in your code:
public partial class Form1 : Form
{
private const string GOODBYE = "Goodbye Cruel World";
private const string HELLO = "Hello World!";
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
if (textBox1.Text.Equals(GOODBYE ))
{
textBox1.Text = HELLO;
}
else { textBox1.Text = (GOODBYE ); }
}
}
If you are using same string in multiple places then its better if you define it as a const and use that everywhere in your code, this will help you in reducing errors like the one you have now (Goodye is Goodbye) and it is also easier to change/maintain.
Check the spelling of Goodye in the else clause. The condition will always be false.

Take User Textbox Input (numbers) put into defined array size and output?

This is "homework" (in my c# book)
What should happen is on a textbox a user inputs 10 numbers (one at a time I would do it) and each time he clicks the button "addValBtn" it should add that number to the array until it fills up 10 spots with 10 user inputted numbers. Then I'm trying to display that array via the displayValBtn (which I can figure out myself) but I just cant get this damn array to work correctly.
My book explained how to set up an array fine, and from what I read on Stackoverflow and off Google people had similar questions. But none of them seemed to take input each time you click the button. So I'm at a loss of what to do exactly.
I created and defined my array as numArray (using double) - set my array index to 10. Then I did a for loop so that it should parse the number from the textbox into the array. But when I run nothing happens. (or as far as Im concerned its working I just havent displayed it back to see if its storing the numbers)
1) Am I doing this correctly for this situation?
2) Since I need to display the contents of the array once its populated via a button, would my variables need to be global?
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;
namespace array
{
public partial class array : Form
{
public array()
{
InitializeComponent();
}
private void exitBtn_Click(object sender, EventArgs e)
{
this.Close();
}
public void addValBtn_Click(object sender, EventArgs e)
{
double[] numArray = new double[10];
for (int index = 0; index < numArray.Length; index++)
{
numArray[index] = int.Parse(intTxtBox.Text);
}
}
private void displayValBtn_Click(object sender, EventArgs e)
{
}
}
}
Am I doing this correctly for this situation?
Sort of, but not really :) The code you have for parsing the input is good, but you are simply assigning all 10 values of the array to the same number.
Also, your array is scoped locally to the addValBtn_Click method, which means it won't stick around past the end of that event handler.
Since I need to display the contents of the array once its populated
via a button, would my variables need to be global?
As I mentioned earlier, your array isn't going to stick around. You are on the right track, but it doesn't need to be a global variable, just class level Form
You need to declare your array once, and then keep pushing values into it when the button is clicked. Be sure to keep track of which index you are on as well.
I declared my "index" in the class like so: int index = 0; and it's
telling me that the field 'array.array.index' is never assigned to.
Doesn't really make sense to me, seeing as how I assigned it a value!
Make sure you are declaring this in the right spot. If you have done everything you say your class declaration should look something like this:
public partial class array : Form
{
private const int MAX_ITEMS = 10;
private int _currentIndex = 0;
private double[] _numArray = new double[MAX_ITEMS];
//SNIP...
}
There shouldn't be any problems with that. If there are, then I probably can't help you without standing over your shoulder :)
You need to do a bit of research on event driven programming.
for (int index = 0; index < numArray.Length; index++)
{
numArray[index] = int.Parse(intTxtBox.Text);
}
This is going to read the same integer into every position of the array.
You need to store "index" in your class and just do something like:
if (this.index < 10)
{
numArray[this.index] = int.Parse(intTxtBox.Text);
this.index++
}

Windows form application - C# Random numer guessing game

I need a little help with a Random Number Guessing Game in visual studio. I got the brunt of the code down but I am having troubles with the Random number generator and getting the random number to port into the click events. As always, I don't really need code but some guidance and/or explanations as to what I am doing wrong and if there is a more effecient way to do things in the beginner phases of learning. Below is my code, the comments are the parts where I am having troubles. Thanks for any help as the help I've recieved to date as been phenominal.
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;
namespace LAB6B
{
public partial class game : Form
{
public game()
{
InitializeComponent();
//Generate Random number between 1 and 100
//Not sure if there is a better way?
Random rand1 = new Random();
int num1 = rand1.Next(1,50);
int num2 = rand1.Next(1,50);
int answer = num1 + num2;
}
private void evaluate_Click(object sender, EventArgs e)
{
int count = 0;
int choice = Convert.ToInt32(guess);
if (guess.Text != string.Empty)
{
// set counter to keep track of how many tries
// should this be done by a loop or will it count without a loop?
count++;
//compare user input against random number
//Can’t import the random number for comparision
if (choice < answer)
{
Evaluate.Visible = false;
lblMessage.Visible = true;
lblMessage.Text = "Too Low!";
Clear.Visible = true;
BackColor = Color.LightSeaGreen;
}
else if (choice > answer)
{
Evaluate.Visible = false;
lblMessage.Visible = true;
lblMessage.Text = "Too High!";
Clear.Visible = true;
BackColor = Color.SlateBlue;
}
else
{
//Display correct message along with how many times it took to get it
MessageBox.Show(" Eso es CORRECTO! It took you {0} tries. ", count);
}
}
}
private void Clear_Click(object sender, EventArgs e)
{
guess.Text = "";
Evaluate.Visible = true;
lblMessage.Visible = false;
Clear.Visible = false;
BackColor = Color.PowderBlue;
}
}
}
As the rand1 and answer variables are defined within the constructor, you can only access them in the constructor. Defining answer on the class level will solve most of the problems, as you will be able to access it both from the constructor and the click handlers, like this:
private int answer;
private int count;
public game()
{
InitializeComponent();
//Generate Random number between 1 and 100
Random random= new Random();
// no need for num1 and num2, it's just as random
answer = random.Next(1,101);
}
I think you have an issue of scope. The "answer" variable is declared inside your constructor, so it will not be visible to the code inside evaluate_Click(…).
Looks like you need to declare answer as a class variable. When you declare a variable in a constructor, it's still local to that method and not available to other methods.
I do not really know what you want answered, but an obvious error is that you must define your count variable as a member variable in order to keep track of the number of tries. As it is now, the count will always be initialized as zero each time the user presses the button.
First of, you need to declare your variable answer in the page level so it can be used by other page level functions.
Do it like this
public partial class game : Form
{
int answer;
public game()
{
}
}
in your counter you can use a static counter or a page level variable also such as the variable answer
just reset the counter when the user have guessed correctly

Categories