I'm kind of stuck on a thing I'm working on.. I have a windows form application with different buttons, and each button is supposed to do different thing. Now my problem:
On one button, when I press it, it should generate random numbers (0-1000 for example) and display the number in a textbox, which I also have on the program. I tried to do this code on the button:
private void button5_Click(object sender, EventArgs e)
{
Random slumpGenerator = new Random(); int tal;
tal = slumpGenerator.Next();
}
But unfortunately, no number is displayed on the text box. And i think it could be because I haven't referred that the numbers should display on my textbox, any ideas?
Well sure - you're not setting any properties on your text box. You're ignoring your newly-generated random number. You'd need something like:
Random slumpGenerator = new Random();
// Or whatever limits you want... Next() returns a double
int tal = slumpGenerator.Next(0, 100);
textBox.Text = tal.ToString();
Note that in general it's a bad idea to create many Random instances - but it's not as simple as making it a static variable... see my article on randomness for more details. Also note how I've changed the code to declare a variable and assign it a value in a single statement - that's generally preferable to declaring in one statement and then assigning it a value later.
private void button5_Click(object sender, EventArgs e)
{
Random slumpGenerator = new Random();
int tal = slumpGenerator.Next(0, 1000);
txtBxName.Text = tal.ToString();
}
You need to add a miniumum and maximum to "Random" .Next() method.
You are not setting the textboxes text value anywhere.
You can consider RNGCryptoServiceProvider thread safe class (System.Security.Cryptography namespace) which is cryptographic Random Number Generator (RNG) using the implementation provided by the cryptographic service provider.
Implementation is a bit more difficult than using System.Random class.
Sample implementation is as follows:
using System.Security.Cryptography;
...
private RNGCryptoServiceProvider rnd = new RNGCryptoServiceProvider();
private int NextInt32(int maxValue)
{
byte[] intBytes = new byte[4];
rnd.GetBytes(intBytes);
return Math.Abs(BitConverter.ToInt32(intBytes, 0)) % maxValue + 1;
}
// And your method with textBox
private void button5_Click(object sender, EventArgs e)
{
textBox.Text = NextInt32(1000).ToString();
}
You can read more on RNGCryptoServiceProvider in SO question: Pros and cons of RNGCryptoServiceProvider
You need to add a few things to your code. Here is the fulll code for what you want...
private void button5_Click(object sender, EventArgs e)
{
Random slumpGenerator = new Random(); int tal;
tal = slumpGenerator.Next(0, 1000);
textBox.Text = tal.ToString();
}
You have to set a minimum and a maximun value you want it to generate. You also have to put the minimum value 1 below what you really want to generate. i.e. if you want to generate a number between 10 and 20, you would need to put the minimum value to 9, and maximum value to 20.
You also need to put the value into a textbox, etc, to show it. Since it is an int, and textbox's text is in a String format, you will need to convert it to a String by putting this at the end of your code: .ToString()
I know this answer is late, but it might be able to help you later!
**Random Number Generation in C#.Net**
Add two namespaces before you write the code
*using System.Security;
using System.Security.Cryptography;*
Code:
Copy and place the following code inside the button
RNGCryptoServiceProvider xx = new RNGCryptoServiceProvider();
byte [] random_number=new byte [512];
xx.GetBytes(random_number);
foreach (var i in random_number)
{
textBox1.Text = i.ToString();
}
for further details in c#.net refer my blogspot : mbthangamalai.blogspot.in
Related
First off I want to say that I am still a beginner with C#, so when explaining information to me, please do not use complex jargon that I will not understand.
Second, I have done most of the work and I am not asking for others to finish my work, I am just asking for help because I do not understand what is wrong/why it is not working.
Third, my program is incomplete, and I cannot finish it unless my random generator is working.
So with that being said, the issue that I am having is when I try to run the program, the system underlines the word "random" in the beginning of my code and says
"A field initializer cannot reference the non-static field, method, or
property".
Why is it doing this? If I put the two line of code inside "Public Guess()" part then the compiler runs fine, it just then says my "if" statement wont work because the container "random" doesn't exist. I'm not sure of what else I could do and I would really, really, appreciate some help.
My code is as follows:
public partial class Guess : Form
{
/*This is a "Guess the number" program. Then this program is run,
* I want to create two containers for the "TryParse" portion of this program
and then I want a number to be randomly generated for the user to guess, then
I want one last container to count how many guess it took the user.*/
string number;
int guess;
Random random;
int randomnumber;
int counter;
public Guess()
{
/*Once the program is initalized, I want the 2nd button hidden until the first one
is clicked with a value in the textbox*/
InitializeComponent();
btnexe2.Hide();
random = new Random();
randomnumber = random.Next(0, 101);
}
private void btnClose_Click(object sender, EventArgs e)
{
//This closes the program//
Close();
}
private void btnexe1_Click(object sender, EventArgs e)
{
/*This is where I will be doing most of my variable checking. First,
I want to check if the user left the textbox empty, if it is then
display a message box saying to enter a number.*/
if (string.IsNullOrEmpty(tbnumber.Text))
{
MessageBox.Show("Please enter a number from 0-100.");
}
else
{/*If it is not empty, then I want the system to determine if the variable
that has been entered can be converted to a int.*/
number = Convert.ToString(tbnumber.Text);
if (Int32.TryParse(number, out guess))
{
/*If the value can be converted, then i want the system to see if
it is lower, higher, or equal to the random value. Then I want the fist button hidden,
and the second one shown. Then I want to record how many times the user guessed.*/
if (guess < randomnumber)
{
btnexe1.Hide();
btnexe2.Show();
this.BackColor = System.Drawing.Color.LightSeaGreen;
lbloutput.Text = "Too Low";
counter=counter + 1;
}
else if (guess > randomnumber)
{
btnexe1.Hide();
btnexe2.Show();
this.BackColor = System.Drawing.Color.SlateBlue;
lbloutput.Text = "Too High";
counter = counter + 1;
}
else
{
lbloutput.Text = "Good Guess";
counter = counter + 1;
}
}
else
{
/*If the value cannot be converted to a int, then display a message box saying so.*/
MessageBox.Show("This is not a number. Please enter a number between 0-100.");
}
}
}
private void btnexe2_Click(object sender, EventArgs e)
{/*I want to check if the user left the textbox empty, if it is then
display a message box saying to enter a number.*/
if (string.IsNullOrEmpty(tbnumber.Text))
{
MessageBox.Show("Please enter a number from 0-100.");
}
else
{/*If it is not empty, then I want the system to determine if the variable
that has been entered can be converted to a int.*/
number = Convert.ToString(tbnumber.Text);
if (Int32.TryParse(number, out guess))
{
/*If the value can be converted, then I want the system to see if
it is lower, higher, or equal to the random value. Then I want to record how
many times the user guessed.*/
if (guess < randomnumber)
{
lbloutput.Text = "Too Low";
this.BackColor = System.Drawing.Color.LightSeaGreen;
counter = counter + 1;
}
else if (guess > randomnumber)
{
lbloutput.Text = "Too High";
this.BackColor = System.Drawing.Color.SlateBlue;
counter = counter + 1;
}
else
{
lbloutput.Text = "Good Guess";
counter = counter + 1;
lblcounter.Text = "You guessed " + counter + " times.";
}
}
else
{
/*If the value cannot be converted to a int, then display a message box saying so.*/
MessageBox.Show("This is not a number. Please enter a number between 0-100");
}
}
}
}
Change your code like this. You are trying to call method Next in the class which is not allowed and when you move complete code inside constructor then your variables scope exist only inside that constructor so variable accessed in another method will not work. So solution is to define variable at class level but initialize it in constructor
Random random;
int randomnumber;
public Guess()
{
/*Once the program is initalized, I want the 2nd button hidden until the first one
is clicked with a value in the textbox*/
InitializeComponent();
btnexe2.Hide();
random = new Random();
randomnumber = random.Next(0, 101);
}
You should initialize variables inside a method (initialization means adding a value to a variable - using "new" keyword);
Try something like this:
class Guess {
Random random;
int randomNumber;
public Guess() {
random = new Random();
randomnumber = random.Next(0, 101);
//Rest of the code
}
}
I think this answer can help you. You can not use an instance variable to initialize another instance variable because the order you write them is not per definition the order the compiler creates them.
A field initializer cannot reference the nonstatic field, method, or property
try changing this
Random random = new Random();
int randomnumber = random.Next(0, 101);
public Guess()
{
/*Once the program is initalized, I want the 2nd button hidden until the first one
is clicked with a value in the textbox*/
InitializeComponent();
btnexe2.Hide();
}
to this
private Random _Random;
private int _RandomNumbrer;
public Guess()
{
_Random = new Random();
_RandomNumbrer = random.Next(0, 101);
/*Once the program is initalized, I want the 2nd button hidden until the first one
is clicked with a value in the textbox*/
InitializeComponent();
btnexe2.Hide();
}
youre nearly there with what youre trying to do
I am creating a windows form that is a random number guessing game. I've made these before in C++ and never had an issue, however I have a big one here- I have no idea how to get the user back to input a number after the loop has began running. Here is my code:
private void btnGuess_Click(object sender, EventArgs e)
{
int guess = 0;
int count = 0;
int accumulator = 0; // accumulator
Random rand = new Random();
int number = rand.Next(1, 100);
txtAnswer.Focus();
while (guess != number)
{
guess = int.Parse(txtAnswer.Text);
if (guess < number)
{
MessageBox.Show("Too Low! Guess again!");
txtAnswer.Text = "";
txtAnswer.Focus();
count++;
accumulator++;
}
else if (guess > number)
{
MessageBox.Show("Too High! Try again!");
txtAnswer.Text = "";
txtAnswer.Focus();
count++;
accumulator++;
}
else
{
MessageBox.Show("Correct! you guessed the number in " + accumulator + " tries!");
break;
}
}
}
}
}
I just filled the while loop arguments with something for you guys, even though i know it won't work. Basically, I need to run the loop, get feedback (if the users guess was too high or low) then get the user to be able to input another number BEFORE the loop runs again. I don't know how to get that to happen with a text box control which is where the input will be. Any ideas?
You should not loop inside in the btnGuess_Click. Instead you need to store the state (the number, count, and the accumulator variables) in the scope of the form itself.
Initialize the random number when the form loads, or using some kind of start button.
Then inside the guess button handler, read the text box value and compare it to the number variable, such as what you are doing currently.
What you are building is more a console style application. So there is 1 main loop that is executing all the code.
In forms applications it is an event driven environment. So the user gets a form, presses a button, the form is evaluated and then the method handling ends.
So you have on a class level some variables for counts, in the constructor you add the initialization and the method for submit will be something like
private void btnGuess_Click(object sender, EventArgs e)
{
//Increment counters
//Check
//Show feedback
//Leave the button click code
}
For some more info, check this out:
https://msdn.microsoft.com/en-us/library/dd492132.aspx
I am trying to code a random generator using a list in the code behind. I am able to get a fully working number generator using the code below but I now want the generator to run through a list of places and not numbers but I'm stuck with it as I am completely new to developing.
Code for random number generator
private void btnGenerate_Click(object sender, EventArgs e)
{
Random Place = new Random();
int Places = Place.Next();
txtResult.Text = Places.ToString();
}
As I said I want my generator to use places to eat (for example) but I am stuck
private void btnGenerate_Click(object sender, EventArgs e)
{
Eat = new List<string>();
Eat.Add("Tesco");
Eat.Add("KFC");
Eat.Add("Subway");
Eat.Add("Chippy");
Random Place = new Random();
int Places = Place.Next();
txtResult.Text = Places.ToString();
}
I tired commenting out the int Places = Place.Next(); and changing txtResult.Text = Places.ToString(); to txtResult.Text = Eat.ToString(); but this causes the following error to display in the field on my application when I click the 'Generate' button
System.Collections.Generic.List`1[System.String]
Try this:
List<string> Eat = new List<string>();
Eat.Add("Tesco");
Eat.Add("KFC");
Eat.Add("Subway");
Eat.Add("Chippy");
Random Place = new Random();
int Places = Place.Next(0, Eat.Count);
txtResult.Text = Eat[Places];
The line int Places = Place.Next(0, Eat.Count);
will generate a random number within the range 0 to Eat.Count - 1.
This will produce a valid index within your list. Then Eat[Places]accesses
the randoly chosen string.
private void button2_Click(object sender, EventArgs e)
{
int a,sum=0;
a = 10;
sum = sum + a;
MessageBox.Show( sum + "Sum Result");
}
Every time I click on the button I get the answer 10. I want to store result. Suppose I click 5 times then there should be 50.The above code for better understanding should give you some idea of what I'm going for.
Other option if possible I get this result outside of the button event by some method. I am new in C# so feeling lot of problem.
As #tnw tried to tell you - move sum outside the function like this:
private sum = 0;
private void button2_Click(object sender, EventArgs e)
{
sum = sum + 10;
MessageBox.Show( sum + "Sum Result");
}
This should work
explanation
The problem you face is that every variable declared inside a function will get initialized every time you call this function and is discarded when you exit the function.
With the variable beeing outside you made it a field of your class and it will be kept in memory as long as the instance you are using (for example the instance of your form) will be.
It is because sum=0; gets re-initialized every time you call the function. Try setting it as a global variable inside the Class and then call it.
This way, when ever the function will be called, the value of sum won't get back to 0, but will increment from where it was left.
// somewhere above
int sum = 0;
// then the function
private void button2_Click(object sender, EventArgs e)
{
sum = sum + 10;
MessageBox.Show(sum + " = Sum Result");
}
..since you're not using a or b. I have removed them. However, if you're using them inside the function (in a code which you haven't posted) please add them back.
Each time you called the function, you created new variable called sum and if gets deleted at the end of the function. So, each time you pressed the button, sum had a value of 0 in it as initially. Adding 10 to it, would always return 10.
Global variables are declared inside the class itself. Every variable inside the function (such as this one) would be recreated each time you call the function and will have the value you're providing it with. So it is a better approach to write the variables globally, whose value is required next time.
Im trying to create a section of a program, where a user presses a button and a image is placed in one of 9 pictureboxes. Each time the button is clicked, a different picturebox should be selected. However, before i get to that, i'm having trouble getting my method to see the arrays i am trying to pass it.
I have 2 arrays, Slots and SlotsUsed and i am trying to initalise them when the program starts. However, when i try to pass them to the method "randomBox" which is called within "Button1" visual studio says they do not exist. How can i make these arrays visible throughout my code?
Many thanks
Anthony
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 pin_program
{
public partial class Mainscreen : Form
{
//Sets where users files are to be stored (for later use)
string activeDir = #"C:\Users\Tony\Downloads\Programs\pin program\Users";
public Mainscreen()
{
InitializeComponent();
}
//method to generate random number
private int RandomNumber(int min, int max)
{
Random random = new Random();
return random.Next(min, max);
}
public void randomBox(int pictureVal, PictureBox[] Slots, bool[] SlotsUsed)
{
//generate random number
int j = RandomNumber(0, 9);
if (SlotsUsed[j] == false)
{
// Create image, assign it and set slots value to used
Image newImage = Image.FromFile(#"C:\Users\Tony\Downloads\Programs\pin program\pin program\pin program\Images\" + pictureVal + ".jpg");
Slots[j].Image = newImage;
SlotsUsed[j] = true;
}
else
do
{
j = RandomNumber(0, 9);
} while (SlotsUsed[j] == false);
return;
}
private void button1_Click(object sender, EventArgs e)
{
//for use later
string userName = textBox1.Text;
//for use later
label1.Visible = true;
//test call of method.
randomBox(1, Slots, SlotsUsed);
}
public void Mainscreen_Load(object sender, EventArgs e)
{
//array for slots
PictureBox[] Slots = new PictureBox[9];
Slots[0] = pictureBox1;
Slots[1] = pictureBox2;
Slots[2] = pictureBox3;
Slots[3] = pictureBox4;
Slots[4] = pictureBox5;
Slots[5] = pictureBox6;
Slots[6] = pictureBox7;
Slots[7] = pictureBox8;
Slots[8] = pictureBox9;
//array for used slots
bool[] SlotsUsed = new bool[9];
for (int i = 0; i != (SlotsUsed.Length); i++)
{
SlotsUsed[i] = false;
}
}
}
}
EDIT:
I dont seem to be able to post comments for some reason, so i'll just ask here. How would i declare my arrays as instance variables instead of local? Does instance variable have another name i might know it by?
CHeers
Currently you're declaring Slots and SlotsUsed as local variables in Mainscreen_Load. They need to be instance variables in your form, as otherwise you can't refer to them elsewhere - and indeed they won't logically exist elsewhere. They're part of the state of your form, so they should be instance variables.
Additionally, your approach for generating random numbers is broken - see my article on random numbers for more information.
I'd also add that you might consider just using a single collection, shuffling it to start with, and then removing items from it as you go - that way you can easily tell when you've run out of images, and you don't have to loop round until you find an unused slot.
well, the easiest way to do this would be to declare a field.
protected PictureBox[] Slots
inside your Form class (outside of any methods.