簡體   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