我有一个ListBoxControl在窗体(Form1)和它下面的一个按钮,我想向我展示另一个窗体(Form2)。从另一个表格添加一个项目到一个ListBoxControl
在Form2中,我有一个TextBox和一个按钮,我希望当我单击此按钮时将TextBox中的当前文本添加到另一个窗体Form1中的ListBoxControl中。
我该怎么做?
形式1:
表格2:
我有一个ListBoxControl在窗体(Form1)和它下面的一个按钮,我想向我展示另一个窗体(Form2)。从另一个表格添加一个项目到一个ListBoxControl
在Form2中,我有一个TextBox和一个按钮,我希望当我单击此按钮时将TextBox中的当前文本添加到另一个窗体Form1中的ListBoxControl中。
我该怎么做?
形式1:
表格2:
有一个使用对话框的标准模式。
public string KeyWord
{
get { return Textbox1.Text; }
}
在Form1上,单击按钮时:
Form 2上,用于读取控制提供财产
using (Form2 dialog = new Form2())
{
// init Form2
var result = dialog.ShowDialog();
if (result == DialogResult.OK)
{
sting newKeyWord = dialog.KeyWord;
// add to listbox
}
}
使用其它形式的在此代码:
Form1 frm;
if ((frm= (Form1)IsFormAlreadyOpen(typeof(Form1))) != null)
{
//get the value of the form
//frm.listboxcontrol.text
}
public static Form IsFormAlreadyOpen(Type FormType)
{
return Application.OpenForms.Cast<Form>().FirstOrDefault(OpenForm => OpenForm.GetType() == FormType);
}
您可以在Form1中创建一个公共方法:
public SampleMethodName(string Value)
{
// Write your code to add it the list.
ListBox1.Add(Value);
}
现在,当用户打开的窗口2,添加一些文本的文本框,然后按[验证, 您可以创建Form1的一个实例。
protected void valider_click(object sender, eventargs e)
{
Form1 frm = new Form1();
frm.SampleMethodName(TextBox.Value);
}
在表格2中,它给了我这个错误: '错误'GestionBib.Form1'没有包含'AddMotCle'的定义,也没有接受类型''的第一个参数的扩展方法'AddMotCle' GestionBib.Form1'可以找到(你是否缺少使用指令或程序集引用?)' –
你在form1中使用公共方法吗?如果是这样,那么它不应该产生异常? – 2012-09-19 12:00:43
如果你不想使用对话框结果(正如Henk所建议的那样),但是如果您想要打开第二个表单,请尝试以下操作。即如果你想在添加ListBox项目时打开第二个窗体。
表1:
using System;
using System.Windows.Forms;
namespace FormComm
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
var form2 = new Form2(this);
form2.Show();
}
delegate void AddListBoxItemCallback(string text);
public void AddListBoxItem(object item)
{
if (this.InvokeRequired)
{
AddListBoxItemCallback callback = new AddListBoxItemCallback(AddListBoxItem);
this.Invoke(callback, new object[] { item });
}
else
{
this.listBox1.Items.Add(item);
}
}
}
}
表2:
using System;
using System.Windows.Forms;
namespace FormComm
{
public partial class Form2 : Form
{
private Form1 _form = null;
public Form2(Form1 form)
{
InitializeComponent();
this._form = form;
}
private void button1_Click(object sender, EventArgs e)
{
_form.AddListBoxItem(textBox1.Text);
}
}
}
是您的关键字的形式模态(的ShowDialog)或无(节目)? –
它是(showDialog) –