I'm very new to C# language, so please take me easy. What I want to ask is quite simple, but being new, I don't know how to do it.
I have 2 forms: Form1 and Form2. Form1 is the "default" one, the one you have when you open the application. I have 2 textboxes in the second form and two buttons (ok and cancel). In the first form I have a button which opens the 2nd form when you click on it and a textbox. I tried to get the text from those 2 textboxes in form 2 and to put it in the textbox from form1, but I didn't managed to do it. I want when I click ok in the second form, the text from those 2 textboxes in form 2 to be put in the textbox from form1 and when I click cancel, to just simply close form2. Can you help me?
You could create a public property in Form2 that is set by Form1 when you press your button.
public string TextValueFromForm1 { get; set; }
On the Form Load event, you could then, set the value of your text box to that of the property.
Example of Form 2
public class Form2 : Form
{
private TextBox textBox1;
private TextBox textBox2;
public string TextValue1 { get; set; }
public string TextValue2 { get; set; }
public Form2()
{
this.Load += new EventHandler((object sender, EventArgs e) =>
{
textBox1.Text = TextValue1;
textBox2.Text = TextValue2;
});
}
}
If I understand your question:
- Form2 has 2 TextBoxes (textBox1
and textBox2
) and 2 buttons (btnOK
and btnCancel
)
- If btnOK
is pressed - concatinate values of textBox1
and textBox2
and pass them to Form1
- If btnCancel
is pressed - do not pass any data
Brief description of my answer:
It can be easily achieved with event handlers, just hook up to OnFormClosing
event and read data from predefined property of Form2
Some code to illustrate my answer is below
Form1.cs
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Form2 frm2 = new Form2();
frm2.Show();
frm2.FormClosing += new FormClosingEventHandler(frm2_FormClosing);
}
void frm2_FormClosing(object sender, FormClosingEventArgs e)
{
if ((sender as Form2).textData != null)
textBox1.Text = (sender as Form2).textData;
}
}
Form2.cs
public partial class Form2 : Form
{
public string textData;
public Form2()
{
InitializeComponent();
}
private void btnOK_Click(object sender, EventArgs e)
{
textData = textBox1.Text + " " + textBox2.Text;
this.Close();
}
private void btnCancel_Click(object sender, EventArgs e)
{
this.Close();
}
}