我正在为我的同事离开我的雇主开发的代码添加一项功能。 我将尝试在一个简单的案例中解释解决方案 -
我有2个表格A和B.
在表单上,我从用户处获取文件夹路径,然后单击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(),因为它会抛出错误
没有超载的方法'开始'取0个参数
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);
}
});
}
答案 0 :(得分:2)
您的代码需要进行首次更改 通过被调用表单的构造函数传递文本框中的信息,然后通过SHOWDIALOG传递表单
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();
}
}
现在以名为save的形式保存全局变量中的传递路径
public class Form1
{
private string _selectedPath = string.Empty;
public Form1(string path)
{
InitializeComponents();
_selectedPath = path;
}
.....
}
现在你可以在表单加载事件中调用SMS系统的初始化(或者更好地覆盖OnLoad事件。)现在这是安全的,因为OnLoad覆盖表单的控件已完全初始化并可以使用< / p>
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
}
答案 1 :(得分:1)
您不能也不应该使用事件委托传递参数。
但有几种可能性:
使用构造函数:
public class FormA : Form
{
public void start()
{
FormB b = new FormB(this.textBox.Text);
}
}
public class FormB : Form
{
public FormB(string s)
{
// use variable s
}
}