pass "out" parameter to ShowDialog?

V

viepia

Hi,
What is the best way to set a "out" variable in a WinForm passed by
a ShowDialog caller?

Currently I am setting a public static variable in the ShowDialog
callers' class in the WinForm - I am hoping there is a less ugly way.

Thanks,
Viepia
 
H

Harvey

You can easily access a public value once the form is closed that
contains the assignment you make in the form. So let's say you have a
main form:

public partial class MainForm : Form
{
public MainForm()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)
{
WinForm wf = new WinForm();
if (wf.ShowDialog().Equals(DialogResult.OK))
MessageBox.Show(wf.SomePublicString);
}
}

You can see the wf.SomePublicString is available to you... Here is the
WinForm:

public partial class WinForm : Form
{
public string SomePublicString
{
get { return somePublicString; }
set { somePublicString = value; }
}
private string somePublicString = string.Empty;

public WinForm()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)
{
SomePublicString = "Hello World!";
DialogResult = DialogResult.OK;
}
}

Hope that helps...
 
N

Nicholas Paldino [.NET/C# MVP]

Viepia,

Why not expose the value through a property on the instance? Then,
after the call to ShowDialog is made, the caller can access the value
through the property on the instance that ShowDialog was called on.
 
I

Ignacio Machin \( .NET/ C# MVP \)

Hi,


A simple public property will do:

MyForm f = new MyForm();
if ( f.ShowDialog() == DialogResult ...)
{
DoSomething( f.MyProperty);
}
 
V

viepia

Thanks for helping my code look clearner. For some dumb reason I
didn't think that the instance data of a closed Winform was valid.

Viepia
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top