【问题标题】:Prevent initial form from "refreshing" when subform is run运行子表单时防止初始表单“刷新”
【发布时间】:2019-07-01 23:29:24
【问题描述】:

我有以下(精炼的)代码:

Form1

public partial class Form1 : Form
{
    GetIP getIP;
    string deviceIP = "";

    public Form1()
    {
        InitializeComponent();

        if (deviceIP == "") 
        {
            getIP = new GetIP();
            var result = getIP.ShowDialog();
            if (result == DialogResult.OK)
            {
                string ip = getIP.IPAddress;
                deviceIP = ip;
            }
        }
    }

    private void Button_Clicked(object sender, EventArgs e)
    {
        form2 = new Form2();
        form2.ShowDialog();
    }
}

获取IP

public partial class GetIP : Form
{
    public string IPAddress { get; set; }
    public GetIP()
    {
        InitializeComponent();
    }

    private void btnConnect_Click(object sender, EventArgs e)
    {
        IPAddress = txtIPAddress.Text;
        DialogResult = DialogResult.OK;
        Close();
    }
}

Form2

public partial class Form2 : Form
{
    Form1 form1 = new Form1(); // oops...this might be it?

    public Form2(string deviceData)
    {
        InitializeComponent();
        // Force CRLF (\r\n) on all newline instances
        deviceData = deviceData.Replace("\r\n", "\n");
        deviceData = deviceData.Replace("\r", "\n"); 
        deviceData = deviceData.Replace("\n", "\r\n");
        txtdeviceData.Text = deviceData;
    }

    private void btnClose_Click(object sender, EventArgs e)
    {
        Close();
    }
}

我的问题是,每当Form2 尝试打开时,Form1 似乎都会刷新。这会导致GetIP 再次运行(这也意味着deviceIP 被重新初始化为“”)。 Form2 直到 GetIP 完成后才会打开。

deviceIP == "" 的检查是我解决问题的尝试,但变量初始化似乎也重新运行,从而使我的检查无效。

有没有办法防止Form1 刷新,或者至少有办法防止GetIP 再次运行?

更新
嗯,我刚刚注意到我有似乎是剩余的代码行,它创建了一个 Form1 实例...

【问题讨论】:

  • 为什么不在form2的构造函数上传IP?
  • Form2 没有需要 IP 的操作。 Form2 确实将数据传递给它,但为了简单起见,我将其省略了。
  • 我们必须查看您的 Form2 代码。不应需要此 if (deviceIP == "") 行。在构造函数期间永远不会为假。
  • @LarsTech 感谢您请求Form2 代码。起初我不确定它会完成什么,但它让我发现了似乎是什么原因:P 是的,就是这样......谢谢!
  • 那一行写着oops this might be it 不会影响Form1 的原始实例,因为deviceIP 不是静态字段。

标签: c# .net winforms


【解决方案1】:
public partial class Form2 : Form
{
    Form1 form1 = new Form1(); // oops...this might be it?

是的,就是那个“哎呀”。

如果 Form2 需要对 Form1 的引用,请尝试通过构造函数传递它:

public partial class Form2 : Form
{
  Form1 form1 = null;

  public Form2(Form1 f1, string deviceData) {
    InitializeComponent();
    form1 = f1;
    // etc, etc.
  }

【讨论】:

    猜你喜欢
    • 2015-03-05
    • 2017-06-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-30
    相关资源
    最近更新 更多