这个问题是以下问题的后续问题: C# Text don't display on another form after double clicking an item in listbox
现在我在form3的文本框中键入了我的值。在form3中按“OK”后,如何将值传递给form1以在listbox10中显示它?下面是我的form3编码,但它不起作用:
private void button1_Click(object sender, EventArgs e)
{
//This is the coding for "OK" button.
int selectedIndex = listBox10.SelectedIndex;
listBox10.Items.Insert(selectedIndex, textBox1.Text);
}
答案 0 :(得分:1)
您可以将公共财产放在form3上:
public partial class form3 : Form
{
public String SomeName
{
get
{
return textbox1.Text;
}
}
...
private void buttonOK_Click(object sender, EventArgs e)
{
DialogResult = DialogResult.OK;
Close();
}
private void buttonCancel_Click(object sender, EventArgs e)
{
DialogResult = DialogResult.Cancel;
Close();
}
}
在form1中,你打开form3,在ShowDialog之后,你会写:
if (form3.ShowDialog() == DialogResult.OK)
{
int selectedIndex = listBox10.SelectedIndex;
if (selectedIndex == -1) //listbox does not have items
listbox10.Add(form3.SomeValue);
else
listBox10.Items.Insert(selectedIndex, form3.SomeName);
}
答案 1 :(得分:0)
做类似的事情:
//form1:
public void add(int num)
{
//add num to the list box.
}
现在,form3应该在构造函数中获取form1的实例,并保存它:
//in form3:
private form form1_i
public form3(form i_form1)
{
.
.
.
form1_i = i_form1;
}
并在按钮上单击form3,在form1中调用fumction add
。
答案 2 :(得分:0)
它应该是这样的,这是最安全的方法,事实上如果你正在使用Windows Mobile,这是不会使应用程序崩溃的唯一方法。在桌面版本中,它可能会在调试版本中崩溃。
public partial class Form1 : Form
{
public string name = "something";
public Form1()
{
InitializeComponent();
}
public delegate void nameChanger(string nme);
public void ChangeName(string nme)
{
this.name = nme;
}
public void SafeNameChange(string nme)
{
this.Invoke(new nameChanger(ChangeName), new object[] { nme });
}
private void button2_Click(object sender, EventArgs e)
{
Form3 f3 = new Form3(this);
f3.Show();
}
}
public partial class Form2 : Form
{
Form1 ff;
public Form2(Form1 firstForm)
{
InitializeComponent();
ff = firstForm;
}
private void button2_Click(object sender, EventArgs e)
{
ff.SafeNameChange("something different from the Form1");
this.Close();
}
}