繁体   English   中英

如何将文本框条目放入while循环? C#

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

这基本上就是我想要做的。 我想允许某人输入他们想要运行特定程序的次数。 我无法弄清楚的是如何将数字10改为(textBox1.Text)。 如果您有更好的方法,请告诉我。 我是编程新手。

int counter = 1;
while ( counter <= 10 )
{
    Process.Start("notepad.exe");
    counter = counter + 1;
}

这显示了如何获取用户提供的输入并将其安全地转换为整数(System.Int32)并在计数器中使用它。

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

尝试使用System.Int32.TryParse(textBox1.Text, out counterMax)MSDN上的文档 )将字符串转换为数字。

如果转换成功,则返回true;如果失败则返回false(即,用户输入的内容不是整数)

textBox1.Text将返回一个字符串。 您需要将其转换为int并且由于它正在接受用户输入,因此您需要安全地执行此操作:

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

我建议使用MaskedTextBox控件从用户那里获取输入,这将有助于我们确保只提供数字。 它不会限制我们使用TryParse功能。

像这样设置掩码:(可以使用“属性窗口”)

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

然后使用这样:

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

使用Try Catch body,就像这个函数一样

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

并使用

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM