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.
Related
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";
new to WPF so not sure if there is some sort of syntax that I am missing or what.
Course choice;
int totalCredits = 0;
int classesRegistered = 0;
string[] registeredCourses = new string[3];
private void button_Click(object sender, RoutedEventArgs e)
{
if (classesRegistered < 3)
{
choice = (Course)(this.comboBox.SelectedItem);
if ((!choice.Equals(registeredCourses[0]))
&& (!choice.Equals(registeredCourses[1]))
&& (!choice.Equals(registeredCourses[2])))
{
registeredCourses[classesRegistered] = choice.ToString();
this.listBox.Items.Add(registeredCourses[classesRegistered]);
classesRegistered = classesRegistered + 1;
}
}
}
So I don't want the choice to be added to the listbox if its already registered to one of the array's values. What is it I'm missing?
Your if statement is comparing a string to a Course object, you may change it to below:
if(!registeredCourses.Any(obj=> obj.Equals(choice.ToString())))
I am currently doing a simili-HangMan project. As I looked through many other projects up here, I haven't found what I was looking for exactly.
Notes:
* The variable motRechercher is the randomized word.
* It can be used everywhere - I did a get set for it.
MY QUESTION IS: I want to display a string in a textbox that is a random word selected from a list, how do I do that?
Here's my code for the textbox:
private void txtMot_TextChanged(object sender, TextChangedEventArgs e)
{
for (int i = 0; i <= motRechercher.Length; i++)
{
StringBuilder sb = new StringBuilder(motRechercher);
sb[i] = '_';
string sba = sb.ToString();
txtMot.Text=sba;
}
}
If the word is for an example : Cat. It should display: _ _ _
Here's my code for the random word selector (It works) - It's mostly to give an idea:
private void btnDemarrer_Click(object sender, RoutedEventArgs e)
{
Random rdn = new Random();
int nbreAleatoire = rdn.Next(0, 27);
motRechercher = lesMots[nbreAleatoire];
}
If you have any questions regarding my code I'll edit it to make it easier for you to understand/help me.
instead of
private void txtMot_TextChanged(object sender, TextChangedEventArgs e)
{
for (int i = 0; i <= motRechercher.Length; i++)
{
StringBuilder sb = new StringBuilder(motRechercher);
sb[i] = '_';
string sba = sb.ToString();
txtMot.Text=sba;
}
}
add another button for next random no to populate to text box.
inside button click do this which will check the length and get the data for you:
private void btnNext_Click(object sender, RoutedEventArgs e)
{
if(motRechercher.Length > 0)
{
String str = new String('_', motRechercher.Length);
txtMot.Text = str;
}
}
If I understand the question, this might be what you're after:
bool changing = false; // variable in class-scope
private void txtMot_TextChanged(object sender, TextChangedEventArgs e)
{
if (changing == false)
{
try
{
changing = true;
String str = new String('_', motRechercher.Length);
txtMot.Text = str;
}
finally
{
changing = false;
}
}
}
Hi People I'm newbie in the C# world and I'm having a problem. I have done an array in the Form_Load method of my program, but I need to access the array in a picture_box method like this:
private void Form2_Load(object sender, EventArgs e)
{
//In this method we get a random array to set the images
int[] imgArray = new int[20];
Random aleatorio = new Random();
int num, contador = 0;
num = aleatorio.Next(1, 21);
imgArray[contador] = num;
contador++;
while (contador < 20)
{
num = aleatorio.Next(1, 21);
for (int i = 0; i <= contador; i++)
{
if (num == imgArray[i])
{
i = contador;
}
else
{
if (i + 1 == contador)
{
imgArray[contador] = num;
contador++;
i = contador;
}
}
}
}
}
private void pictureBox1_Click(object sender, EventArgs e)
{
pictureBox1.Image = Image.FromFile(#"C:\Users\UserName\Desktop\MyMemoryGame\" + imgArray[0] + ".jpg");
}
But I only get the error: Error 1 The name 'imgArray' does not exist in the current context
You need to define int[] imgArray at the class level (outside of Form2_Load) rather than inside it. Otherwise the "scope" of that variable is limited to that function. You will need to knock off the first "int[]" part in Form2_Load to prevent you from just declaring a new variable.
For example:
public class MyClass
{
private int[] myInt;
public void Form2_Load(...) {
myInt = ...;
}
}
The error means exactly what it says.
You've declared the array in the scope of the Form2_Load function. Outside of it, it will not exist.
To do what you're trying to achieve, add a private array to the form itself.
private int[] _imgArray = new int[20];
private void Form2_Load(object sender, EventArgs e)
{
//Setup the imgArray
}
private void pictureBox1_Click(object sender, EventArgs e)
{
//_imgArray is now available as its scope is to the class, not just the Form2_Load method
}
Hopefully that helps.
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.