gpt4 book ai didi

c# - Form_Load() - 传递参数

转载 作者:太空宇宙 更新时间:2023-11-03 21:29:38 25 4
gpt4 key购买 nike

我正在为离开我雇主的同事开发的代码添加一个功能。我将尝试在一个简单的案例中解释解决方案 -

我有 2 个表格 A 和 B。

在 A 表单上,我从用户那里获取文件夹路径,然后单击 A 上的按钮。

在单击表单 A 的按钮时,我需要将路径传递给表单 B 的方法 M。我公开了方法 M,并在表单 A 的 button_click 中编写了以下代码。

private void startButton_Click(object sender, EventArgs e)
{
startButton.Enabled = false;
pathTextBox.Enabled = false;
using (Form1 form1 = new Form1())
{
// This is what I am trying to do. Initially start() did not had any input parameters, now I have added a single input parameter to it.
form1.start(pathTextBox.Text);
}

//this.Close();
}

Now, this works except that FormA_Load() is defined like this -

private void FormA_Load(object sender, EventArgs e)
{
start();
}

问题是我如何将 pathBox.Text 传递给 FormA_Load(),因为它会抛出错误

No overload for method 'start' takes 0 arguments

public void start(string selectedPath)
{
try
{
this.Cursor = Cursors.WaitCursor;
SMSManager smsManager = new SMSManager (selectedPath);
smsManager .CopyCompletedHandler += new SMSManager .CopyCompleted(smsManager_CopyCompletedHandler);
smsManager .CopyLogFiles();
}
catch (Exception ex)
{
WriteLog(ex);

smsManager _CopyCompletedHandler("Error :" + ex.Message, false);
this.Cursor = Cursors.Default;
MessageBox.Show(ex.Message);
}
}

void smsManager_CopyCompletedHandler(string data, bool isFullyCompleted)
{
Invoke((MethodInvoker)delegate
{
this.Text = "SMS Collector- Copying...";
txtStatus.AppendText(stepNo + ". " + data + Environment.NewLine + Environment.NewLine);
txtStatus.ScrollToCaret();
stepNo++;
if (isFullyCompleted)
{
this.Cursor = Cursors.Default;
this.Text = "SMS Collector- Completed";
MessageBox.Show(this, data, "Message", MessageBoxButtons.OK,
MessageBoxIcon.Information);
}
});

}

最佳答案

您的代码需要的第一个更改。
通过被调用表单的构造函数传递文本框中的信息,然后显示表单

private void startButton_Click(object sender, EventArgs e)
{
startButton.Enabled = false;
pathTextBox.Enabled = false;
using (Form1 form1 = new Form1(pathTextBox.Text))
{
// ShowDialog is required to stop the execution here
// Otherwise the code exits immediately and the using destroys the form1 instance
form1.ShowDialog();
}
}

现在以调用的形式将传递的路径保存在全局变量中

public class Form1 
{
private string _selectedPath = string.Empty;
public Form1(string path)
{
InitializeComponents();
_selectedPath = path;
}
.....
}

现在您可以在表单加载事件中调用 SMS 系统的初始化(或者更好地覆盖 OnLoad 事件。)现在这是安全的,因为在 OnLoad 覆盖中表单的控件已完全初始化并准备好使用

protected override void OnLoad(EventArgs e)
{
// The code here will be executed before the Form.Load event
start(_selectedPath);
base.OnLoad(e);
// The code here will be executed after the Form.Load event
}

关于c# - Form_Load() - 传递参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24991890/

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