Hi @Shaifali jain , Welcome to Microsoft Q&A,
There are indeed multiple ways to get the value in a subform,
For example, use public properties or use delegates.
Here's how to use public properties:
Form1
private void button1_Click(object sender, EventArgs e)
{
Form2 form2 = new Form2();
form2.ShowDialog();
MessageBox.Show("The return value is: " + form2.returnString);
}
Form2
public partial class Form2 : Form
{
public string returnString;
public Form2()
{
InitializeComponent();
}
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
returnString = textBox1.Text;
}
}
Here's how to use delegation: Add delegates and events to child windows. Set up the child window to call the above event and pass the string that needs to be passed to the event to the event. Add a method to display the returned information in the main window, the same as participating in the MyAccountDelegate delegation. Call the event in the main window.
Form1:
private void button1_Click(object sender, EventArgs e)
{
Form2 form2 = new Form2();
form2.MyAccountEvent += new Form2.MyAccountDelegate(DisplayMyAccount);
form2.ShowDialog();
MessageBox.Show("The return value is: " + returnString);
}
private string returnString;
private void DisplayMyAccount(string account)
{
returnString = account;
}
Form2:
public partial class Form2 : Form
{
public delegate void MyAccountDelegate(string account);
public event MyAccountDelegate MyAccountEvent;
public Form2()
{
InitializeComponent();
}
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
if (textBox1.Text.Length > 0)
{
MyAccountEvent(textBox1.Text);//Add account information
}
}
}
Best Regards,
Jiale
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.