Graham
Graham

Reputation: 120

passing to a form which is already open

What I'm trying to do it load some information from a database.

To do this I open a form that lists everything that can be loaded.

When you click load I want to pass the ID back to the original form.

However I can't seem to be able to call a method in that form.

Any help would be appreciated.

Upvotes: 0

Views: 1315

Answers (4)

Gerrie Schenck
Gerrie Schenck

Reputation: 22368

The proper way to do this is to introduce a Controller class which is used by both forms. You can then use a property on the Controller, when that is set will trigger the NotifiyPropertyChanged event.

see INotifyPropertyChanged for more info

Upvotes: 0

Richard Friend
Richard Friend

Reputation: 16018

Why not create a public property for the selected item in the dialog form, something like this.

public int SelectedItemId {get;private set;}

//In your item selected code, like button click handler..
this.SelectedItemId = someValue;

Then just open the form as a Dialog

//Open the child form
using (var form = new ChildForm())
{
    if (form.ShowDialog(this) == DialogResult.OK)
    {
        var result = form.SelectedItemId;//Process here..
    }
}

Upvotes: 0

WraithNath
WraithNath

Reputation: 18013

You could add a property to your form class and reference it from your other form.

eg.

public class FormA : Form
{

private string _YourProperty = string.empty;

public string YourProperty
{
 get
 {
  return _YourProperty;
 }
 set
 {
  _YourProperty = value;
 }
}

}

public class FormB : Form
{

public void ButtonClick(object sender, EventArgs args)
{
 using (FormA oForm = new FormA)
 {
  if (oForm.ShowDialog() == DialogResult.OK)
  {
   string Variable = oForm.YourProperty;
  }
}
}

You just need to set your property on a button click on form A then you can access it from form B }

Upvotes: 0

Fredrik Mörk
Fredrik Mörk

Reputation: 158309

I would flip this around:

  1. Make the selection form into a modal dialog that is created and displayed by the form where you want to load something
  2. Expose the selection made in the dialog through a property or method in the dialog form

This way the selection form will be decoupled from the caller, and can be reused wherever it makes sense without the need to modify it.

In the selection dialog form class:

public string GetSelectedId()
{
    return whateverIdThatWasSelected;
}

In the calling form:

using(var dlg = new SelectionDialogForm())
{
    if (dlg.ShowDialog() == DialogResult.OK)
    {
        DoSomethingWithSelectedId(dlg.GetSelectedId());
    }
}

Upvotes: 1

Related Questions