我正在向已离开雇主的同事开发的代码添加一项功能。 我将尝试用一个简单的案例来解释解决方案 -
我有 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/