I'm working on a project which generates a random number by taking a input from a textBox then after the click of a button, it generates the number and puts it in a Label.
I want to put the text like this:
public void Button_Click(object sender, RoutedEventArgs e)
{
string inputstr;
inputstr = textBox1.Text;
int inputnum;
inputnum = Convert.ToInt32(inputstr);
var me = new MainWindow();
Random rnd = new Random();
int outnum = rnd.Next(inputnum);
string outnum1 = outnum.ToString();
Label.Text = outnum1;
}
but it gives an error which is:
Severity Code Description Project File Line Suppression State
Error CS0117 'Label' does not contain a definition for 'Text' RandomNumber C:\Users\Nameless\source\repos\RandomNumber\RandomNumber\MainWindow.xaml.cs 37 Active
I would be really thankful to anyone who helps.
Several issues/points about your code.
Label.Text
You're trying to assign the Text property to the class itself, that doesn't work. You have to assign the Content property to your instance, for example a label with ID outputLabel. This becomes: outputLabel.Content = "Whatever...";.
Random not being random (enough)
Check this question on StackOverflow: Random number generator only generating one random number
When declaring a Random instance inside your method, it won't be as random as you might want it to be. At least eclare it like following (even better would be from the answer in thlinked question):
private readonly Random rnd = new Random();
public void Button_Click(object sender, RoutedEventArgs e)
{
int outnum = rnd.Next();
}
Inline declaration
Your whole code could be shortened by declaring and assigning variables in one line of code:
private readonly Random rnd = new Random();
public void Button_Click(object sender, RoutedEventArgs e)
{
string inputstr = textBox1.Text;
int inputnum = Convert.ToInt32(inputstr);
int outnum = rnd.Next(inputnum);
yourLabel.Content = outnum.ToString();
}
Other points
Why type var me = new MainWindow(); when you never use it?
You could use var to declare variables
You should validate input when converting from string to int
Try this one:
I just change Label to label1
and comment out var me statement
private void button1_Click(object sender, EventArgs e)
{
string inputstr;
inputstr = textBox1.Text;
int inputnum;
inputnum = Convert.ToInt32(inputstr);
//var me = new MainWindow();
Random rnd = new Random();
int outnum = rnd.Next(inputnum);
string outnum1 = outnum.ToString();
label1.Text = outnum1;
}
Waarom een nieuw MainWindow maken?
Geef de link naar de tag door
<Label x:Name="label1"/>
Error-> label1.Text = "abc";
Right -> label1.Content="abc";
Related
Hi so I am new to programing I just started school and I wanted to get a head start on programing so please keep in mind that everything I show you is all self-taught. Here is my question I wanted to make a random number guessing game and for the most part it works but every time you click the button to guess it randoms a different number which I don’t want here is what I have so far
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
// number of guesses
int numberOfGesses = 0;
private void btnCalc_Click(object sender, EventArgs e)
{
// make the generator
Random generator = new Random();
//make the number
int number = generator.Next(1, 10);
// get the users guess
int guess = int.Parse(txtInput.Text);
//check the users guess
if (guess == number)
{
lblAnswer.Text = "You got it";
numberOfGesses = 0;
}
else if (guess != number)
{
numberOfGesses = numberOfGesses + 1;
lblAnswer.Text = "try agian you have gessed" + (numberOfGesses) + " times";
}
}
}
I know it keeps creating a new number because every time I press the guess button it starts from the top and makes a new number. I tried to take this block and make it global but I got an error
// make the generator
Random generator = new Random();
//make the number
int number = generator.Next(1, 10);
again im realy new and i found this site when lookinging up some qeustions i had so i thought it would be a good place to help me learn about programing while i wait till i can get into the programing classes thank you for your time.
You likely got an error because C# doesn't allow you to assign a default value of a field based on another field.
public partial class Form1 : Form {
int numberOfGuess = 0;
Random generator = new Random();
int number;
// other methods
}
generator can be initialized before or after number, hence the error. Instead, you can put it in the form intializer (Form1 method), or make another button and click it and generate a new random number:
public partial class Form1 : Form
{
// number of guesses
int numberOfGesses = 0;
Random generator = new Random();
int number;
public Form1()
{
InitializeComponent();
// Generate the random number
number = generator.Next(1, 10);
}
private void btnRandom_Click(object sender, EventArgs e)
{
// Generate a new random number when you click a button on the form
number = generator.Next(1, 10);
}
private void btnCalc_Click(object sender, EventArgs e)
{
// get the users guess
int guess = int.Parse(txtInput.Text);
//check the users guess
if (guess == number)
{
lblAnswer.Text = "You got it";
numberOfGesses = 0;
}
else if (guess != number)
{
numberOfGesses = numberOfGesses + 1;
lblAnswer.Text = "try agian you have gessed" + (numberOfGesses) + " times";
}
}
}
You cannot use an instance variable to initialize another instance variable. Why? Because the compiler can rearrange these - there is no guarantee that generator will be initialized before number, so the above line might throw a NullReferenceException.
So change the default number value to 0:
Random generator = new Random();
int number = 0;
Initialise in the constructor:
public Form1()
{
InitializeComponent();
number = generator.Next(1, 10);
}
When the button is clicked generate the number since here you will be needing it:
private void btnCalc_Click(object sender, EventArgs e)
{
//take the input & Compare as before.
}
I am building a program that on a button click displays a random line from a text file into a text box.
I am only a beginner at C# so I am not sure where I have gone wrong.
private void startButton_Click(object sender, EventArgs e)
{
int lineCount = File.ReadAllLines(#"D:...\QUESTIONS.text").Length;
Random rnd = new Random();
int randomLineNum = rnd.Next(lineCount);
int indicator = 0;
using (var reader = File.OpenText(#"D:...\QUESTIONS.text"))
{
while (reader.ReadLine() != null)
{
if (indicator == randomLineNum)
{
questionBox.Text = reader;
break;
}
indicator++;
}
}
}
Can you also help me figure out where this code is supposed to go.
Thank you for your help in advance! : )
you can remove many complexities in your code.
private Random r = new Random();
private void startButton_Click(object sender, EventArgs e)
{
var lines = File.ReadAllLines(#"D:...\QUESTIONS.text");
questionBox.Text = lines[r.Next(lines.Length)];
}
defining a random variable outside the function scope and reuse it
every time is a known best practice.
why reading the file twice? you are reading it once with ReadAllLines and then again with an StreamReader
This should do it:
private void startButton_Click(object sender, EventArgs e)
{
var lines = File.ReadAllLines(#"D:...\QUESTIONS.text");
int lineCount = lines.Length;
Random rnd = new Random();
int randomLineNum = rnd.Next(lineCount);
questionBox.Text = lines[randomLineNum];
}
There is no need to read the same file twice, so keep the lines in a local variable to access it later.
I have 2 listbox, one for 'names' and one for 'what they did' I have a textbox assigned to each of these listbox and an add button for each so the user can enter whatever 'name' or 'what they did' they want into the 2 listbox. I have a create button which will show the result of this in a message box and thats easy, but I want it to show a random combination each time.
So in the 'name' listbox I could have entered the names Jerry, Dean, Mary and in the 'what they did' I could have entered Sat, Slept, Cried. On the press of the create button I want a random item from both lists so the result could be 'Dean Cried' then the next time I press create it could be 'Jerry Slept'
I have been able to, with some help get a random item on each press of the create button from the name box but I am having trouble getting my code to make it happen for both.
private void btnaddname_Click(object sender, EventArgs e)
{
stringname = textBoxname.Text;
textBoxname.Clear();
listboxname.Items.Add(stringname);
}
private void btnaddwhat_Click(object sender, EventArgs e)
{
stringwhat = textBoxwhat.Text;
textBoxwhat.Clear();
listBoxwhat.Items.Add(stringwhat);
}
private void buttoncreate_Click(object sender, EventArgs e)
{
Random random = new Random();
int randomNumber = random.Next(1, listboxname.Items.Count);
listboxname.Select();
listboxname.SelectedItem = listboxname.Items[randomNumber];
Random randomwhat = new Random();
int randomnumwhat = randomwhat.Next(1, listBoxwhat.Items.Count);
listBoxwhat.Select();
listBoxwhat.SelectedItem = listBoxwhat.Items[randomnumwhat];
MessageBox.Show(listboxname.SelectedItem.ToString() + (" ") + (listBoxwhat.SelectedItem.ToString()));
}
Try to create just one Random variable and use it for both list...
Random random = new Random();
int randomNumber = random.Next(1, listboxname.Items.Count);
listboxname.Select();
listboxname.SelectedItem = listboxname.Items[randomNumber];
int randomnumwhat = random.Next(1, listBoxwhat.Items.Count);
listBoxwhat.Select();
listBoxwhat.SelectedItem = listBoxwhat.Items[randomnumwhat];
MessageBox.Show(listboxname.SelectedItem.ToString() + (" ") +(listBoxwhat.SelectedItem.ToString()));
I am making a random number generator in a form application and the user will type a number in a text box. When user clicks on the OK button. the text in the textbox will be stored in a string value. for example;
if (ButtonOK is clicked)
{
String a = textbox1;
int b = int.Parse(a);
}
Then the value of the textbox will become a labels value. for example:
b = label1.Text;
how do i do that?
I would be really happy if anyone could help me solve this problem.
SOLVED thanks to Soner Gönül
I feel like you need something like;
private void ButtonOK_Click(object sender, EventArgs e)
{
string a = textbox1.Text;
int b;
if (Int32.TryParse(a, out b))
{
label1.Text = b.ToString();
}
}
Assuming is a WinForm application just drag a button and a textbox on the form, double click on the button and write this code:
private void button1_Click(object sender, EventArgs e)
{
int max;
if (!int.TryParse(textBox1.Text, out max))
{
label1.Text = "Not a number";
}
else
{
Random r = new Random();
int random = r.Next(max);
label1.Text = string.Format("Random number: {0}", random);
}
}
This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Random number generator not working the way I had planned (C#)
Hi,
Below is the complete code for a small app I am writing - it returns an ArrayList of alphanumeric codes. The problem I have is that when 'stepping' through the code the e.Result is returned correctly with each item being different. However, if I let the app run without the breakpoints I just get multiple instances of the same variable back:
public partial class AlphaNum : Form
{
public AlphaNum()
{
InitializeComponent();
// Initialise BackGroundWorker Reporting
backgroundWorker1.WorkerReportsProgress = true;
// Initialise BackGroundWorker Cancel
backgroundWorker1.WorkerSupportsCancellation = true;
}
private void button1_Click(object sender, EventArgs e)
{
backgroundWorker1.RunWorkerAsync();
button1.Enabled = false;
}
private int RandomNumber(int min, int max)
{
Random random = new Random();
return random.Next(min, max);
}
public string RandomString(Random r, int len)
{
string str = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890";
StringBuilder sb = new StringBuilder();
while ((len--) > 0)
sb.Append(str[(int)(r.NextDouble() * str.Length)]);
return sb.ToString();
}
private string generateCode()
{
Random rnd = new Random();
int length = int.Parse(stringLength.Text);
string code = "";
code = RandomString(rnd, length);
return code;
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
int quantity = int.Parse(quantityRequired.Text);
ArrayList codes = new ArrayList();
string myText = "";
for (int a = 0; a < quantity; a++)
{
myText = generateCode();
codes.Add(myText);
backgroundWorker1.ReportProgress(((100 / quantity) * a));
}
e.Result = codes;
}
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
progressBar1.Value = e.ProgressPercentage; //update progress bar
//Console.WriteLine(time);
//in this example, we log that optional additional info to textbox
}
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
button1.Enabled = true;
ArrayList codes = new ArrayList();
codes = (ArrayList)e.Result;
for (int i = 0; i < codes.Count; i++ )
{
outputText.Text += codes[i].ToString();
outputText.AppendText(Environment.NewLine);
}
}
}
}
Can anyone explain why the result is okay when I effectively slow the process down by stepping my way through but incorrect when it runs without being stopped/slowed down?
Many Thanks
The loop in backgroundWorker1_DoWork is so fast that the Random object generated in generateCode is always seeded with the same value, thus producing the same values. Don't recreate the Random object but assign one to an instance variable in the constructor of your class and only use that one.
You shouldn't create a new Random object every time you need a random number.
Random rnd = new Random();
uses the current time to initialize the LFSR, when the program runs at full speed, the same "current time" gets used many times in a row.