gpt4 book ai didi

c# - 奇怪的错误(输入字符串的格式不正确。)

转载 作者:行者123 更新时间:2023-12-02 10:47:11 25 4
gpt4 key购买 nike

这是我的代码:

namespace Class_Properties {
public partial class Form1 : Form {
private string firstHeight1 = "";
public int firstHeight {
get {
return Convert.ToInt32( firstHeight1 );
}
}

public Form1() {
InitializeComponent();
}

private void button1_Click( object sender, EventArgs e ) {
firstHeight1 = textBox2.Text;

Form2 secondForm = new Form2();
secondForm.Show();
}
}
}

然后是另一类:
namespace Class_Properties {
public partial class Form2 : Form {
public Form2() {
InitializeComponent();
Form1 mainWindow = new Form1();
this.Height = mainWindow.firstHeight;
}
}
}

运行时,键入 200作为 textbox2的值,然后单击 button1,然后Visual Studio说以下异常:

我该怎么办才能解决此错误?

最佳答案

这是失败的原因:

        InitializeComponent();
Form1 mainWindow = new Form1();
this.Height = mainWindow.firstHeight; //<--

不管您对另一个 Form1进行了什么操作,它都不会出现在此代码中,因为它是 firstHeight == string.Empty的新实例,将无法解析。

您必须将现有的Form1发送到Form2:
public Form2(Form1 parent)
{
this.Height = parent.firstHeight;
}

// called like so from Form1:
var form2 = new Form2(this);

尽管诚然,最好只发送您需要的东西:
public Form2(int desiredHeight)
{
this.Height = desiredHeight;
}

// called like so from Form1:
var form2 = new Form2(this.firstHeight);

关于c# - 奇怪的错误(输入字符串的格式不正确。),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12696246/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com