Thursday, April 12, 2012

C# pass data/value between forms.




This method pass parameter from one form to another when user clicks OK.

First create property in Second Form, which we want to pass parameter to calling form

Place your cursor below the Form Class.(e.g. public partial class Form2:Form)

Create variable to hold property value.

private strting strString;
//create property
public string strRetVal
{
get{return strString;}
set{strString=value;}//value is predefined keyword, it will automatically assign value to strString from the code.

}


Now click on Form's OK button click event.

//assign value to private strString variable.
strString="ABC" //or any value you are getting from your code i.e. textbox1.text

Now move to Form1

Show Form2 as a ShowDialog

if (form2.ShowDialog() == DialogResult.OK)
{
string strReturnedValue=form2.strRetVal; //Access form2's property.

}