AndB
AndB

Reputation: 139

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;
}

Upvotes: 2

Views: 2122

Answers (5)

a d
a d

Reputation: 572

use Try Catch body ,like this function

bool ErrorTextBox(Control C)
    {
        try
        {
            Convert.ToInt32(C.Text);
            return true;
        }
        catch { return false; }
    }

and use

Upvotes: 0

NeverHopeless
NeverHopeless

Reputation: 11233

I would suggest to use MaskedTextBox control to take input from user, which will help us to ensure that only numbers will supplied. It will not bound us for TryParse functionality.

Set mask like this: (can use "Property Window")

MaskedTextBox1.Mask = "00000";   // will support upto 5 digit numbers

then use like this:

int finalRange = int.Parse(MaskedTextBox1.Text);
int counter = 1;
while ( counter <= finalRange )
{
    Process.Start("notepad.exe");
    counter = counter + 1;
}

Upvotes: 0

WildCrustacean
WildCrustacean

Reputation: 5966

Try System.Int32.TryParse(textBox1.Text, out counterMax) (Docs on MSDN) to convert a string to a number.

This will return a true if the conversion succeeded or a false if it failed (i.e., the user entered something that isn't an integer)

Upvotes: 2

David
David

Reputation: 73594

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).");
}

Upvotes: 5

Foggzie
Foggzie

Reputation: 9821

textBox1.Text will return a string. You need to convert it into an int and since it's taking user input, you'll want to do so safely:

int max;
Int32.TryParse(value, out max);
if (max)
{
    while ( counter <= max ) {}
}
else
{
    //Error
}

Upvotes: 2

Related Questions