之间的字符串我在C#以下的Windows窗体程序:传递形式
表1对一个ListBox和按钮。当按下按钮时,它将显示Form2上有一个TextBox和Button。当按下Form 2上的按钮时,它将把文本放到Form1上的列表框中。下面是每个表格的代码,然后是我正在使用的类。任何建议都会很棒。
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Form2 frm2 = new Form2();
frm2.NewTextChanged += new EventHandler<CustomEvent>(form2_NewTextChanged);
frm2.ShowDialog();
// Unsubscribe from event
frm2.NewTextChanged -= form2_NewTextChanged;
frm2.Dispose();
frm2 = null;
}
private void form2_NewTextChanged(object sender, CustomEvent e)
{
//Text = e.Text;
lbItem.Items.Add(e.Text);
}
}
public partial class Form2 : Form
{
public event EventHandler<CustomEvent> NewTextChanged;
private string newText;
public Form2()
{
InitializeComponent();
}
public string NewText
{
get { return newText; }
set
{
if (newText != value)
{
newText = value;
OnNewTextChanged(new CustomEvent(newText));
}
}
}
protected virtual void OnNewTextChanged(CustomEvent e)
{
EventHandler<CustomEvent> eh = NewTextChanged;
if (eh != null)
eh(this, e);
}
private void btnSendToForm1_Click(object sender, EventArgs e)
{
newText = textBox1.Text;
}
}
public class CustomEvent : EventArgs
{
private string text;
public CustomEvent(string text)
{
this.text = text;
}
public string Text
{
get { return text; }
}
}
我想用一个自定义的处理程序。有任何建议吗?
_When表格2按下按钮,就会把文成在Form1上ListBox中我已经更新了答案,对不起错了一个 –
之前。我想使用一个自定义的处理程序。当form2上的按钮被按下时,form2应该关闭吗?或者这种情况可能发生多次,每次按下按钮时?也许你的意思是自定义** Event **而不是“处理程序”? –
当我单击form2上的按钮使其添加到表单1上的列表框时,不会添加任何内容。 – JPJedi