由于某些奇怪的原因,解析int不起作用



我有第二个表单,点击按钮后会弹出,用户可以为方法输入一些参数,将输入保存在变量中,然后我将结果解析为int(因此我可以在方法中使用它(。现在,在解析它时,该值看起来是NULL,与用户在文本框中输入的内容相反。

var displayproperties = new int[3];
using (Form2 form = new Form2())
{
try
{
if (form.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
int i = 0;
while (i == 0) 
{
if (form.click) // ok button is clicked
{
// parse values
displayproperties[0] = int.Parse(form.Height);
displayproperties[1] = int.Parse(form.Width);
displayproperties[2] = int.Parse(form.Framerate);
goto break_0; // break out of loop ( loop is to check when button is clicked )
}
}
}
}

正如您在这里看到的,用户输入的值分别是HeightWidthFramerate。正如我所解释的,它将其解析为int,并将其存储在displaypropertiesint数组中。这是第二种形式:

public string Height { get; set; }
public string Width { get; set; }
public string Framerate { get; set; }
public bool click = false; 
public Form2()
{
InitializeComponent();
}
private void Form3_Load(object sender, EventArgs e){}
private void textBox1_TextChanged(object sender, EventArgs e)
{
Height = height.Text; 
}
private void textBox2_TextChanged(object sender, EventArgs e)
{
Width = width.Text; 
}
private void textBox3_TextChanged(object sender, EventArgs e)
{
Framerate = framerate.Text; 
}
public void OK_Click(object sender, EventArgs e)
{
click = true;            
}

最终,这些值被传递到这个类中:public Class1(int width, int height)然而,我得到了一个超出范围的异常,表示该值必须大于零。不用说,当60在其他地方使用时,我输入的值肯定大于零(分别为80060060(。

由于我的评论建议对您有效,我将添加它作为答案。

根据您所说的,听起来您可能没有在任何地方设置DialogResult,因此您的if语句永远不会被输入,因为条件不满足。

您应该在OK_Click:中设置对话框结果并关闭表单

public void OK_Click(object sender, EventArgs e)
{
this.DialogResult = DialogResult.OK;
this.Close();       
}

然后你应该从你的主表单中删除额外的代码:

var displayproperties = new int[3];
using (Form2 form = new Form2())
{
try
{
if (form.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
// parse values
displayproperties[0] = int.Parse(form.Height);
displayproperties[1] = int.Parse(form.Width);
displayproperties[2] = int.Parse(form.Framerate);
}
}
}

对话框结果将用作click属性,因此不再需要此属性。顺便说一句,我建议切换到TryParse,这样您就可以主动检查输入值是否是有效的整数,而不是等到抛出异常时才检查。

例如:

string a = "hello"; // substitute user input here
int result;
if (!int.TryParse(a, out result))
{
MessageBox.Show($"{a} isn't a number!");
return;
}
MessageBox.Show($"Your integer is {result}");

如果您是编程新手,我建议您熟悉如何使用调试器。在代码中设置断点并检查值会很快发现问题所在。微软有一个教程。

最新更新