Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I put a textbox entry into while loop? C#

This is essentially what I am trying to do. I want to allow someone to enter a number on how many times they want to run a specific program. What I can't figure out is how to change the number 10 into (textBox1.Text). If you have a better way please let me know. I am very new to programming.

int counter = 1;
while ( counter <= 10 )
{
    Process.Start("notepad.exe");
    counter = counter + 1;
}
like image 853
AndB Avatar asked Jun 11 '26 00:06

AndB


1 Answers

This shows how to take the user-supplied input and safely convert it to an integer (System.Int32) and use it in your counter.

int counter = 1;
int UserSuppliedNumber = 0;

// use Int32.TryParse, assuming the user may enter a non-integer value in the textbox.  
// Never trust user input.
if(System.Int32.TryParse(TextBox1.Text, out UserSuppliedNumber)
{
   while ( counter <= UserSuppliedNumber)
   {
       Process.Start("notepad.exe");
       counter = counter + 1;  // Could also be written as counter++ or counter += 1 to shorten the code
   }
}
else
{
   MessageBox.Show("Invalid number entered.  Please enter a valid integer (whole number).");
}
like image 62
David Avatar answered Jun 15 '26 05:06

David