Passing Parameters back and forth between forms in C# - c#

I am creating an application where a user will click a button on form1, which will cause form2 to display. The user will then fill out a chat on form2 and then click a button that will close form2 and send back parameters to form1 for processing. How can I do this in C#? I have seen people using properties to do this, but the examples are not clear enough. Can someone give some example code showing me how I can pass the parameters? I would prefer the properties method, but as long as it works, I will count it as the answer.

Put simply, place your form elements in the second form as you typically would. Then, you can add public accessors to that form that you can then pull from and reference. For instance, if Form2 has a text fields you wanted to pull back, you could:
class Form2
{
// Form2.designer.cs
private TextBox TextBox1;
// Form2.cs
public String TextBoxValue // retrieving a value from
{
get
{
return this.TextBox1.Text;
}
}
public Form2(String InitialTextBoxValue) // passing value to
{
IntiializeComponent();
this.TextBox1.Text = InitialTextBoxValue;
}
}
Then just access it later when you create the form (much like the OpenFileDialog does for Filename etc.
public void Button1_Click(object sender, EventArgs e)
{
Form2 form2 = new Form2("Bob"); // Start with "Bob"
form2.ShowDialog(); // Dialog opens and user enters "John" and closes it
MessageBox.Show(form2.TextBoxValue); // now the value is "John"
}
Same thing can be done for Int32, Boolean, etc. Just depends on the form's value, if you'd like to cast/validate it, or otherwise.
Alternativly, you can play with the Modifiers property within the form designer where you can make the control public so it's accessible externally. I personally recommend using an accessor so you can validate and confirm the returned results rather than just dumping the value (as this logic is typically found in the form itself, not in every instance you want to call/use Form2)

Here is how I like to pass parameter(s) to and back from another form:
Provided the following form design for Form1 and Form2:
In this example, the 'txtBoxForm1' textbox on Form1 is passed to Form2 where it is used to initialize the 'txtBoxForm2' textbox on Form2. After the user interacts with Form2 and ends it by clicking on the [Return to Form1] button, the value of the 'txtBoxForm2' textbox is assigned to the parameter that is returned (by reference) to the 'txtBoxForm1' textbox on Form1.
Coding this is done in two simple steps:
Step 1) In Form1, pass parameter(s) to Form2 by overloading the ShowDialog() method:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnSend_Click(object sender, EventArgs e)
{
Form2 f2 = new Form2();
//Step 1)
//Display the form passing parameter(s) via overloading
//the ShowDialog() method.
//In this example the parameter is the 'txtBoxForm1' on Form1.
// f2.ShowDialog(); is replaced by
f2.ShowDialog(ref txtBoxForm1);
}
}
In the above code, the parameter is the 'txtBoxForm1' textbox itself that is passed by reference. Passing it by reference is why it not only passes the textbox value to Form2, but it can also receive and display on Form1 any modification applied to that textbox parameter while executing Form2.
I put the whole Form1 class to show that nothing else is special in this class than the overloading of the 'f2.ShowDialog()' method call.
Step 2) Receiving and returning parameter(s) via the overloaded ShowDialog() method:
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
private void btnReturn_Click(object sender, EventArgs e)
{
this.Close();
}
//Step 2)
//Receiving and returning parameter(s) via the overloaded ShowDialog() method.
//This saves the need to have Properties and or fields associated
//to parameters when overloading the above Form() constructor instead.
public void ShowDialog(ref TextBox txtBoxForm1)
{
//Assign received parameter(s) to local context
txtBoxForm2.Text = txtBoxForm1.Text;
this.ShowDialog(); //Display and activate this form (Form2)
//Return parameter(s)
txtBoxForm1.Text = txtBoxForm2.Text;
}
}
Again I supplied the complete form class (Form2 in this case) code to show how limited is the coding intervention. No additional field or property are required here. That is because I used the 'ShowDialog()' instruction here rather than the Form2() constructor from Form1 to pass the parameter.
Contrary to the Form2() constructor, The ShowDialog() method is an envelope around the user interaction phase with Form2. As such, its timing allows the '(ref txtBoxForm1)' parameter to be the complete and sufficient representative of the parameter we wish to send and receive.
Overloading a method by re-declaring it with a different set of parameters (also called signature), is a powerful feature of C# .net. In this case here, it allows on one hand to add parameter(s) to the call of the 'ShowDialog()' method and on the other hand the overloaded method loses nothing from the original version of this same method because the original version of the ShowDialog() .net framework method is executed as well via the 'this.ShowDialog();' instruction.
That is it for me about this for now.
Hoping this helps!

Related

How to access the same object from another Form C#? [duplicate]

I would like to set comboBox.SelectedValue when I select the row in my dataGridView on first form to populate comboBox with that value on another form,
On second form in my load event I have comboBox.DataSource, DisplayMember, ValueMember set it correctly but nothing is happening when I set selectedValue on first. Everything works great when I do it on one form
Form in Windows Forms is a class like other C# classes. The way of communicating between forms are the same as classes. You can consider this options when communicating between classes:
Manipulate second Form from first Form
You can add suitable parameters to the constructor of the second form. Then you can pass values to the constructor when creating an instance of the second form. In the second form store parameters in member fields and use them when you nees.
You can create public property or method in the second form and set those properties after creating an instance of the second form. This way you can use them when you need in the second form. This option is not limited to passing values when creating the second form. You can even use that property during the execution of second Form. Also it's useful for getting a value from it.
As another option you can make the control which you want to manipulate it public and this way you can access to it from other form. Using a method is a more recommended way of doing this.
Manipulate first Form from second form
You can create a public method or property in first form and pass an instance of the first form to second form. Then using that method/property on the passed instance, you can manipulate the first form.
You can create an event in second form and after creating an instance of second form subscribe for it in first form and put the code for changing the form in the handler. Then it's enough to raise the event in second form.
You can define a public property of type Action or some other delegate type in second form and then after creating an instance of second form, assign the property using a custom action. Then in second form, it's enough to invoke the action when you need to manipulate first form.
Also here you can make a control of first form to be public and then if you pass an instance of the first form to the second form, you can manipulate the control. It's recommended to use other solutions. It's like creating public property or method, but a method which performs specific task on the control is better that exposing the whole control. But you may need this solution some times.
Here are some useful examples about above solutions.
Manipulate second Form from first Form
Example1 - Using constructor of second Form
Use this example when you need to pass some data to second form, when creating the second form.
public partial class Form2 : Form
{
int selectedValue;
public Form2(int value)
{
InitializeComponent();
selectedValue = value;
}
private void Form2_Load(object sender, EventArgs e)
{
//Load data
this.comboBox1.DataSource = new MyDbContext().Categories.ToList();
this.comboBox1.DisplayMember = "Name";
this.comboBox1.ValueMember = "Id";
this.comboBox1.SelectedValue = selectedValue;
}
}
Then in your first form, it's enough to pass the value to Form2 when you create a new instance of it:
var value = 2; // Or get it from grid
var f = new Form2(value);
f.ShowDialog();
Example2 - using public Property or Method of second Form
Use this example when you need to pass some data to second form, when creating or even after creation of second form.
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
public string SomeValue
{
get { return textBox1.Text;}
set { textBox1.Text = value;}
}
}
Then in your first form, it's enough to pass the value to Form2 when you need, after creating Form2 or whenever you need to set value of textBox1 on Form2:
var f = new Form2(); //value is not needed here
f.SomeValue = "some value";
f.Show();
//...
f.SomeValue = "some other value";
Example 3 - Making a Control of Second form public
Use this example when you need to change a property of a control on second form, when creating or even after creation of second form. It's better to use public property or method instead of exposing whole control properties.
In your Form, at designer, select the control and in Properties window set the Modifiers property to Public. Also make sure the GenerateMember property is true. Then you can simply access this control using its name from outside of the Form.
var f = new Form2();
f.textBox1= "some value";
Manipulate first Form from second form
Example 4 - Create public Method or Property in first Form and pass an instance of First Form to constructor of second Form
Use this example when you need to change first Form from second Form.
In your Form1, create a property of a method that accepts some parameters and put the logic in it:
public void ChangeTextBox1Text(string text)
{
this.textBox1.Text = text;
}
Then create a constructor in Form2 which accepts a parameter of type Form1 and keep the passed value in a member field and use it when you need:
Form1 form1;
public Form2 (Form1 f)
{
InitializeComponent();
form1 = f;
}
private void button1_Click(object sender, EventArgs e)
{
form1.ChangeTextBox1Text("Some Value");
}
Now when creating Form2 you should pass an instance of Form1 to it:
var f = new Form2(this);
f.Show();
Example 5 - Using event of second Form in first Form
Take a look at this post. It's about communication between form and a control, but it's applicable to communication between forms also.
Example 6 - Injection an Action in second Form
Take a look at this post. It's about communication between form and a control, but it's applicable to communication between forms also.
Example 7 - Making a Control of first form public
In this solution you need to make a control in first form public, like example 3. Then like example 4 pass an instance of the first form to second form and keep it in a field and use it when you need. Using a public method or property is preferred.
Form1 form1;
public Form2 (Form1 f)
{
InitializeComponent();
form1 = f;
}
private void button1_Click(object sender, EventArgs e)
{
form1.textBox1.Text = "Some Value";
}
when creating Form2 you should pass an instance of Form1 to it:
var f = new Form2(this);
f.Show();

Calling a method from a different form

I have 2 forms. First one (Form1) has a datagrid, the second one (Form2) has a button to call a function in Form1 to refresh the datagrid.
All i want to achieve is; on clicking the button in form2 , form1 datagrid should refresh (this refresh will be as a result of calling the function temp_proj )
How can i achieve this?
You can make a class where you store the instance of your form1.
You can call your form1 update method like
Globals.Form1.UpdateUI() from another class. You can either instantiate in your class or store it as a variable in global class.
Here you can use the delegates and events concepts. Consider the following code segments:
Code in Form1(the one which having the grid)
delegate void RefreshGrid();
// Method or event that opens form 2
public void OpenNextForm()
{
RefreshGrid EventRefresh = new RefreshGrid(RefreshGridEvent);
Form2 frm2Instance = new Form2();
frm2Instance.parentEvent = EventRefresh;
frm2Instance.Show();
}
Code in Form2
public Delegate parentEvent;
public void Form2ButtonClick()
{
parentEvent.DynamicInvoke();
}
Please note the following:
Form2ButtonClick: will be the button click event from the Form2
OpenNextForm : will be the event in Form1 that opens the Form2

c# passing string to different form textbox [duplicate]

I would like to set comboBox.SelectedValue when I select the row in my dataGridView on first form to populate comboBox with that value on another form,
On second form in my load event I have comboBox.DataSource, DisplayMember, ValueMember set it correctly but nothing is happening when I set selectedValue on first. Everything works great when I do it on one form
Form in Windows Forms is a class like other C# classes. The way of communicating between forms are the same as classes. You can consider this options when communicating between classes:
Manipulate second Form from first Form
You can add suitable parameters to the constructor of the second form. Then you can pass values to the constructor when creating an instance of the second form. In the second form store parameters in member fields and use them when you nees.
You can create public property or method in the second form and set those properties after creating an instance of the second form. This way you can use them when you need in the second form. This option is not limited to passing values when creating the second form. You can even use that property during the execution of second Form. Also it's useful for getting a value from it.
As another option you can make the control which you want to manipulate it public and this way you can access to it from other form. Using a method is a more recommended way of doing this.
Manipulate first Form from second form
You can create a public method or property in first form and pass an instance of the first form to second form. Then using that method/property on the passed instance, you can manipulate the first form.
You can create an event in second form and after creating an instance of second form subscribe for it in first form and put the code for changing the form in the handler. Then it's enough to raise the event in second form.
You can define a public property of type Action or some other delegate type in second form and then after creating an instance of second form, assign the property using a custom action. Then in second form, it's enough to invoke the action when you need to manipulate first form.
Also here you can make a control of first form to be public and then if you pass an instance of the first form to the second form, you can manipulate the control. It's recommended to use other solutions. It's like creating public property or method, but a method which performs specific task on the control is better that exposing the whole control. But you may need this solution some times.
Here are some useful examples about above solutions.
Manipulate second Form from first Form
Example1 - Using constructor of second Form
Use this example when you need to pass some data to second form, when creating the second form.
public partial class Form2 : Form
{
int selectedValue;
public Form2(int value)
{
InitializeComponent();
selectedValue = value;
}
private void Form2_Load(object sender, EventArgs e)
{
//Load data
this.comboBox1.DataSource = new MyDbContext().Categories.ToList();
this.comboBox1.DisplayMember = "Name";
this.comboBox1.ValueMember = "Id";
this.comboBox1.SelectedValue = selectedValue;
}
}
Then in your first form, it's enough to pass the value to Form2 when you create a new instance of it:
var value = 2; // Or get it from grid
var f = new Form2(value);
f.ShowDialog();
Example2 - using public Property or Method of second Form
Use this example when you need to pass some data to second form, when creating or even after creation of second form.
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
public string SomeValue
{
get { return textBox1.Text;}
set { textBox1.Text = value;}
}
}
Then in your first form, it's enough to pass the value to Form2 when you need, after creating Form2 or whenever you need to set value of textBox1 on Form2:
var f = new Form2(); //value is not needed here
f.SomeValue = "some value";
f.Show();
//...
f.SomeValue = "some other value";
Example 3 - Making a Control of Second form public
Use this example when you need to change a property of a control on second form, when creating or even after creation of second form. It's better to use public property or method instead of exposing whole control properties.
In your Form, at designer, select the control and in Properties window set the Modifiers property to Public. Also make sure the GenerateMember property is true. Then you can simply access this control using its name from outside of the Form.
var f = new Form2();
f.textBox1= "some value";
Manipulate first Form from second form
Example 4 - Create public Method or Property in first Form and pass an instance of First Form to constructor of second Form
Use this example when you need to change first Form from second Form.
In your Form1, create a property of a method that accepts some parameters and put the logic in it:
public void ChangeTextBox1Text(string text)
{
this.textBox1.Text = text;
}
Then create a constructor in Form2 which accepts a parameter of type Form1 and keep the passed value in a member field and use it when you need:
Form1 form1;
public Form2 (Form1 f)
{
InitializeComponent();
form1 = f;
}
private void button1_Click(object sender, EventArgs e)
{
form1.ChangeTextBox1Text("Some Value");
}
Now when creating Form2 you should pass an instance of Form1 to it:
var f = new Form2(this);
f.Show();
Example 5 - Using event of second Form in first Form
Take a look at this post. It's about communication between form and a control, but it's applicable to communication between forms also.
Example 6 - Injection an Action in second Form
Take a look at this post. It's about communication between form and a control, but it's applicable to communication between forms also.
Example 7 - Making a Control of first form public
In this solution you need to make a control in first form public, like example 3. Then like example 4 pass an instance of the first form to second form and keep it in a field and use it when you need. Using a public method or property is preferred.
Form1 form1;
public Form2 (Form1 f)
{
InitializeComponent();
form1 = f;
}
private void button1_Click(object sender, EventArgs e)
{
form1.textBox1.Text = "Some Value";
}
when creating Form2 you should pass an instance of Form1 to it:
var f = new Form2(this);
f.Show();

How do I capture the value of a text box and use it as a variable?

Let me preface this by saying I am very new to C# and I am converting a program from VB.net to C#.
I'm working in Visual Studio 2012 and running a SQL Server 2008R2
OK, So I have a form, Form1. on this form is a Text box a user can fill out, TextBox1. Now I want to use the information in the text box as a variable to pull information from a database and populate a text box (textbox2) on a different form (form2) this is the code I am currently using on form 2
private void form2_Load(object sender, EventArgs e)
{
string Name = Form1.TextBox1.Text;
this.TBMainTableAdapter.FillBy(Name);
}
I've also tried loading it like this:
this.TBMainTableAdapter.FillBy(Form1.TextBox1.Text);
these both give me the "Object reference is required for a non-static field... error
In VB.Net it was a lot easier, I coded it like this, and it worked perfectly.
Private Sub Form2_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Me.TBMainTableAdapter.FillBy(Me.ProjectDataset.TBName, TextBoxName.Text)
End Sub
Is there something I am missing in the code behind? I tried changing the code on the text box
from
public System.Windows.Forms.TextBox TextBox1;
to
public static System.Windows.Forms.TextBox TextBox1;
While this cleared up the errors on pulling the variable, it threw a bunch more errors in the code-behind on form 1, the "cant be accessed with an instance, give it a nametype" error
Would it be worth it to change all the errors on the code behind. and more importantly is that the right way to do this?
OK so I added these 2 under
public partial class Form1 : Form
Form1 form1;
public Form2(Form1 frm)
{
form1 = frm;
}
Form2 frm = new Form1(this);
Im getting the "Method must have a return type error" at the "Public Form2(Form1 frm)" line
and
"error Namespace.Form1 does not have a constructor that takes 1 arguments" at the Form2 frm = new Form1(this); line
also if I put the getter property in Form1, I get an error about declaring 2 objects with the same name. Cant find anywhere that declares TextBox1 except in the code behind where its declared at the very end of the code behind as
public System.Windows.Forms.TextBox TxtBox1
and if I put the getter below that, I get an only assignment, call, etc can be used as a statement error
You need to have a reference to the Form1 in your Form2 object in order to use the content of the control from the Form1. Moreover, your textBox1 should be declared public or you should create the getter property for it. You can use a lot of things but if Form1 is needed in the the Form2, then the simplest thing you could do is to pass the reference of the Form1 through the constructor of the Form2.
Form1 form1;
public Form2(Form1 frm)
{
form1 = frm;
}
Add the getter property for the textBox1 in the Form1:
public TextBox TextBox1
{
get
{
this.textBox1;
}
}
You can call this constructor from the Form1 method like this:
From2 frm = new Form2(this);
and then you could call:
private void form2_Load(object sender, EventArgs e)
{
string Name = form1.TextBox1.Text;
this.TBMainTableAdapter.FillBy(Name);
}
Maybe i'm missing something, but the method FillBy takes two parameters, first is the DataTable to fill and the second the Name, so change it to:
this.TBMainTableAdapter.FillBy(Me.ProjectDataset.TBName, Name);
The method with one parameter is TBMainTableAdapter.Fill(DataTable table).
Edit: overlooked that you are on Form2 but the TextBox is on Form1 as Nikola has pointed out, that's of course an important fact. I Keep this answer since it might be helpful anyway.

passing something from child form to parent

so i have this form and on it is a combo box populated from a database via a SQL method.
and i have another form which allows us to maintain the database table etc.
so i make a new instance of the second form doing:
Form1 frm = new Form2;
frm.show();
once i have done what ever i wanted to do on the second form and i close it, i need to somehow trigger an event or something which will refresh the combo box and the code behind it.
i was thinking of some onchange or focus event for the whole form, the problem is i have 5 of these combo boxes and running all the SQL again.
i also thought of passing somesort of variable thro but then i would still need an event for that.
any ideals would be awesome
I think you had your answer in the question... Use an event / handler to refresh.
E.g.
public class Form2 : Form
{
public event EventHandler DbChanged;
protected virtual void OnDbChanged()
{
... // Raise event
}
// On OK button/FormClosing/Closed whatever, be sure to call OnDbChanging
}
Then in your Form1 code
var form2 = new Form2();
form2.DbChanged += new EventHandler(Form2_DbChanged); // Add method to handle change and update the appropriate combo box
form2.Show();
If you've assigned these forms with the first form owning the second, like this:
Form2 frm2 = new Form2();
//assuming that you're launching this form from within the first form
frm2.Owner = this;
then you can get a reference to the first form through the Owner property, and thus call methods on it.
Form2_FormClosed(object o, FormClosedEventArgs e)
{
this.Owner.updateComboBox();
}
Note that you'll need the FormClosing event if you want to send data from the form's controls back, though.
Note that the Owner property has some other special characteristics. Notably, the child form will remain showing (on top) when the parent form is selected.
You can use delegate and event here.
Your parent class will create an object of child class and will also subscribe to the event if child class.
Whenever child class need to pass something/ signal parent class, it will raise an event.
As parent has subscribed to these event, it it will get that data and do the required operation.
Hope this helps you.
Forms are classes. Like any other class, they can have properties and events.
Your Form2 can expose a "DatabaseChanged" event. Form1 or any other form that cares can subscribe to that event. When the database changes, Form2 can fire that event, Form1 will see it and update the combo box.
Lots of options, but a simple one is passing the main form as a reference to the second form.
Form2 frm = new Form2( this );
frm.Show();
Then when Form2 finishes its work, it can call some method on the main form to update
public class Form2 : Form
{
public Form2( Form1 form1 )
{
this.form1 = form1;
}
/// ...
public void Work()
{
// ...
form1.Update( someData );
}
}
Not necessarily ideal from a maintenance perspective, but workable for small apps.
Suppose your combo name id cmb1 and
cmb1.DataSource = ds1;
and you need to call a new window do some work there & whenever you close that window your parent will refresh or cmb1 will have the latest data.
from you parent window call your chlid window like this
if (NameOfWindow.RequestAction(ref ds1)) // let RequestAction is a method
{
///refresh your data source of combo
}
and in the child window the method should be like this:
public static bool RequestAction(ref ds1)
{
NameOfWindow frm = new NameOfWindow();
if (frm.ShowDialog() == DialogResult.OK)
{
//do what ever you want to do and update the ds1
return true;
}
else
{
return false;
}
}

Categories