C#输入字符串错误
我也在尝试输入用户值,并从中倒数秒,但每当我输入任何内容并单击开始按钮时,它都会显示输入字符串格式不正确。我在谷歌上搜索了又搜索,不知道如何让用户输入并解析它,或者将它转换成int和倒计时,当然,同时通过定时器更新标签。 我习惯于控制台应用程序,但我仍然对语法耿耿于怀C#输入字符串错误,c#,winforms,syntax,C#,Winforms,Syntax,我也在尝试输入用户值,并从中倒数秒,但每当我输入任何内容并单击开始按钮时,它都会显示输入字符串格式不正确。我在谷歌上搜索了又搜索,不知道如何让用户输入并解析它,或者将它转换成int和倒计时,当然,同时通过定时器更新标签。 我习惯于控制台应用程序,但我仍然对语法耿耿于怀 using System; using System.Windows.Forms; namespace Countdown { public partial class Form1 : Form {
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 test=int.Parse(txtBoxInput.Text);”代码中有两个问题 第一个问题是您没有保护代码不受无效输入的影响。如果未在txtBoxInput中键入内容,或者键入无法转换为整数的文本,则会出现无效字符串格式异常 第二个问题是变量测试。您在按钮单击中本地声明它,并且假设您没有得到编译错误,那么您就没有使用在计时器滴答声事件中使用的相同名称设置全局类级别变量 所以,每次需要处理用户输入时,都要使用TryParse。这不会在出现问题时引发异常,只会返回true或false。最后,不要在按钮单击中重新声明int test变量,而是直接在TryParse的输出中使用全局类级别变量
public void btnStart_Click(object sender, EventArgs e)
{
// Try to convert the input in an integer. If this succeed you have
// the global variable _test_ set to converted text
if(!Int32.TryParse(txtBoxInput.Text, out test)
MessageBox.Show("Invalid input. Please type a number!");
else
tmrCountdown.Start();
}
将
Parse
更改为TryParse
,查看哪些值无法解析:
public void btnStart_Click(object sender, EventArgs e)
{
if (int.TryParse(txtBoxInput.Text, out test))
// We succeed in parsing, so we continue with the timer
tmrCountdown.Start();
else {
// We failed in parsing
// Let's put keyboard focus on the problem text box...
if (txtBoxInput.CanFocus)
txtBoxInput.Focus();
// ... and report what's been happened
MessageBox.Show($"'{txtBoxInput.Text}' is not a valid integer value",
Application.ProductName,
MessageBoxButtons.OK,
MessageBoxIcon.Warning);
}
}
在您的按钮上尝试此代码
int test=Convert.ToInt32(txtBoxInput.Text);
tmrCountdown.Interval = test*1000; //have to multiply to 1000 since timer interval value is in milliseconds.
tmrCountdown.Start();
只需在文本框中输入整数,数字就可以工作了(虽然它不会从数字开始倒数),但字母/符号会出错。有没有更正确的方法可以做到这一点,我正在努力学习好的做法我尝试每天编写一次任何简单的代码来提高我的学习速度
int
还有一种TryParse
方法,你可能想研究一下。现在,您只需假设输入可以转换为整数,当然情况并非总是如此。如果int.TryParse
返回false,则向用户显示一条错误消息,而不是像现在这样创建一个未捕获的异常。谢谢你们两位,我忘记了需要进行多少检查,现在我需要修复我的计时器循环,无论我输入什么数字,它都保持在0,可能是因为int test=0;hmm@LiamVallance:非常正确,您应该使用test
字段,而不是局部变量(我已经删除了int test=0;
)这样认为,现在可以正常工作了。谢谢你们所有人都能忍受这个问题,特别是我问的所有问题。我确实把我学到的一切都保存在一个代码片段程序中,以便将来对我有所帮助:)