PDA

Click to See Complete Forum and Search --> : [RESOLVED] Passing a variable from one form to another


Beast777
Jun 13th, 2007, 10:25 AM
I know this should be easy and I have been trying many examples with no luck. In VB I would just create a global module and boom done. Not so easy in C# it seems.

I have a MDI parent that opens a form. On that form there is a button and once clicked it opens another form that basically just asks the user to pick from a combobox. Then the user clicks the button and it returns to the original form with the value. If anyone could throw together even two forms both with a button and a textbox and when on form1 they click the button it opens form2 and on form2 you type in a value and click the button and it shows in form1, I think that would clarify it. But please paste your entire code for each form. I have been at this for some time and need to figure this out or just go back to VB.

wossname
Jun 13th, 2007, 12:05 PM
Don't ask for code here. It won't make you very popular.

All you need to do is shadow the ShowDialog() method of the form class and have it return whatever data type you like. Then you can redefine the DialogResult as the same datatype and return it just as if it were a normal showdialog call.

Easy and watertight.

korven
Jun 13th, 2007, 01:08 PM
I don't know if this is exactly what you want, but here goes

Form 1:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace TwoForms
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void btnFrm1_Click(object sender, EventArgs e)
{
Form2 f2 = new Form2();
f2.Show();
f2.Tag = this;

}

public void SetText(string text)
{
txtFrm1.Text = text;
}
}
}


Form 2:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace TwoForms
{
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}

private void Form2_Load(object sender, EventArgs e)
{

}

private void btnFrm2_Click(object sender, EventArgs e)
{
((Form1)this.Tag).SetText(txtFrm2.Text);
this.Close();
}
}
}

pjrage
Jun 14th, 2007, 02:08 PM
I asked a similar question here. Hope the answer helps!

http://www.vbforums.com/showthread.php?t=470000

Edit: Didn't see that this was resolved, sorry. But there is a link for more info for future searchers! :)