There are two forms with code (c # winforms vs2010):

Form1 public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { Form2 frm2 = new Form2(); if (frm2.ShowDialog(this) == DialogResult.OK) { listBox1.Items.Add(frm2.getItem()); } frm2.Close(); frm2.Dispose(); } } From2 public partial class Form2 : Form { public Form2() { InitializeComponent(); button1.DialogResult = DialogResult.OK; button2.DialogResult = DialogResult.Cancel; } public string getItem() { return textBox1.Text; } } 

Can you please tell me how to fix the code if there is one more button on form2 "button3.DialogResult = DialogResult.OK;"? Those. the user can press either button1 or button3 on the form2, which work as "DialogResult.OK".

Those. for button3:

 if (frm2.ShowDialog(this) == DialogResult.OK) { listBox1.Items.Add(frm2.getItem3()); } public string getItem3() { return textBox2.Text; } 
  • Has corrected a question - olga

1 answer 1

 public partial class Form2 : Form { private TextBox itemBox = null; public Form2() { InitializeComponent(); button1.DialogResult = DialogResult.OK; button3.DialogResult = DialogResult.OK; button2.DialogResult = DialogResult.Cancel; } public string getItem() { return (itemBox == null)? null : itemBox.Text; } private void button1_Click(object sender, EventArgs e) { itemBox = textBox1; } private void button3_Click(object sender, EventArgs e) { itemBox = textBox2; } } 
  • Thanks, I will try! - olga
  • @olga Do not forget to connect event handlers to the buttons. - Igor
  • In the code "if (frm2.ShowDialog (this) == DialogResult.OK)" for button3_Click does not work. The textBox2 value is not returned. Only textBox1 is returned. - olga
  • @olga Bad business (. Did you assign the DialogResult button? - Igor
  • DialogResult.OK for button1. And if you press button3, then itemBox is not equal to textBox2? - olga