我想要輸入的用戶數值並以秒爲單位倒計時,但每當我輸入任何內容並單擊開始按鈕時,它說輸入字符串格式不正確。我用google搜索了一下,並且無法弄清楚如何讓用戶輸入和解析,或者將它轉換爲int和倒計時,同時通過定時器更新標籤。 我使用到控制檯應用程序仍然包裹我周圍的語法頭...C#輸入字符串錯誤
using System;
using System.Windows.Forms;
namespace Countdown {
public partial class Form1 : Form
{
int seconds; string user; int test = 30;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void tmrCountdown_Tick(object sender, EventArgs e)
{
lblDisplay.Text = test.ToString();
if (test > 1)
{
lblDisplay.Text = test.ToString() + " Seconds Remaining";
}
else if (test == 1)
{
lblDisplay.Text = test.ToString() + " Second Remaining";
}
else
{
tmrCountdown.Stop();
}
test--;
}
public void btnStart_Click(object sender, EventArgs e)
{
int test = int.Parse(txtBoxInput.Text);
tmrCountdown.Start();
}
private void txtBoxInput_TextChanged(object sender, EventArgs e)
{
}
}
}
錯誤是在「INT測試= int.Parse(txtBoxInput.Text);」
之前任何事情的數字工作(雖然它不會從這個數字倒數),但當然字母/符號錯誤了。有沒有更正確的方法來做到這一點,我試圖學習良好的做法,我嘗試編寫任何代碼甚至每天簡單一次,以提高我的學習速度 –
'int'也有'TryParse'方法,您可能想要看看那個。現在你只是簡單地假設輸入可以被轉換爲一個整數,這當然不總是這樣。如果'int.TryParse'返回false,則向用戶顯示錯誤消息,而不是像現在這樣創建未捕獲的異常。 – oerkelens