Use a variable declared in one form, in another form c#

I have this little project here, where i have declared a variable named "dir" with a directory selected in a Folder Browser dialog in my form called main.cs:

namespace XmoSupportTools
{
public partial class Main : Form
{
    public string dir;

    public FolderBrowserDialog xmodialog { get; private set; }
    public DialogResult xmodialogresult { get; private set; }

    //metoder der bliver brugt senere
    public void startxmo()
    {
        string startfile = dir + "\\xmo.exe";
        Process xmoappli = new Process();

        if (File.Exists(startfile))
        {
            xmoappli.StartInfo.FileName = startfile;
            xmoappli.Start();
        }
        else
        {
            MessageBox.Show("XMO.exe blev ikke fundet på den valgte lokation!");
            File.Delete(dir + "\\xmo.ini");
            dialog();
        }

    }

    public void dialog()
    {

        xmodialog = new FolderBrowserDialog();
        xmodialog.Description = "Find dit XMO Directory:";
        xmodialogresult = xmodialog.ShowDialog();
        if (xmodialogresult == DialogResult.OK)
        {
            dir = xmodialog.SelectedPath;

        }

I want to use that "dir" variable in my second form called Kunde.cs:

public void startxmo()
    {
        string startfile = dir + "\\xmo.exe";
        Process xmoappli = new Process();

        if (File.Exists(startfile))
        {
            xmoappli.StartInfo.FileName = startfile;
            xmoappli.Start();
        }
        else
        {
            MessageBox.Show("XMO.exe blev ikke fundet på den valgte lokation!");
            File.Delete(dir + "\\xmo.ini");
            dialog();
        }

    }

Upvotes: 1

Views: 2295

Answers (6)

Tochukwu Nkemdilim
Tochukwu Nkemdilim

Reputation: 108

You can set create dir as a static variable and set the protection level to the scope of how much you want the variable dir to be accessivle to other forms in your application

{access specifier} static int dir = "path";

{access specifier} could be public, protected internal, protected etc., as depending on it.

Then call dir via dot notation:

Main.dir.ToString();

e.g.

public partial class Form1 : Form
{
    protected internal static int dir = 54;

    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        Form2 a = new Form2();
        a.Show();
    }
}

public partial class Form2 : Form
{
    public Form2()
    {
        MessageBox.Show(Form1.dir.ToString());
        InitializeComponent();
    }
}

Upvotes: 0

Timon Post
Timon Post

Reputation: 2889

In program.cs set mainform instance to public static

public static Lapphantering mainForm;        
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]

static void Main()
{
    mainForm = new Mainform(); // create instance of Lapphantering
    Application.Run(mainForm);
}

In your mainform:

   public partial class Main : Form
   {
      public string dir;

       //code
   }

In your other class:

 public void startxmo()
 {

    //access dir variable from main form instance in program.cs
    string startfile = program.mainform.dir + "\\xmo.exe";
    Process xmoappli = new Process();

    if (File.Exists(startfile))
    {
        xmoappli.StartInfo.FileName = startfile;
        xmoappli.Start();
    }
    else
    {
        MessageBox.Show("XMO.exe blev ikke fundet på den valgte lokation!");
        File.Delete(program.mainform.dir + "\\xmo.ini");
        dialog();
    }

}

So now you can access string dir in main from in every class via Program.cs mainform instance.

Upvotes: 2

Mohit S
Mohit S

Reputation: 14064

You can simply do this in Kunde.cs by writing

System.Windows.Forms.Form f = System.Windows.Forms.Application.OpenForms["MainForm"]; 
//Whatever is the Name of the Form
//than
string kundedir = ((MainForm)f).dir;

Another way of doing it would be you can create a parameterized constructor for calling Kunde and then in MainForm

Kunde k = new Kunde(dir);

in Kunde.cs

string kundedir;
Kunde(string dirval)
{
    kundedir = dirval;
}

Upvotes: 1

netchkin
netchkin

Reputation: 1384

this heavily depends on the application lifecycle, and I am not really versed in winforms, but, if you could hook up Kunde class with Main class, e.g. like this:

public partial class Main : Form
{
  private Kunde _kunde;

  public Main(Kunde kunde)
  {
     _kunde = kunde;
  }

  public void dialog()
  {
    xmodialog = new FolderBrowserDialog();
    xmodialog.Description = "Find dit XMO Directory:";
    xmodialogresult = xmodialog.ShowDialog();
    if (xmodialogresult == DialogResult.OK)
    {
        dir = xmodialog.SelectedPath;
        _kunde.Dir = dir;
    }
  }

  // rest of your code...
}

public class Kunde 
{
  public string Dir { get; set; }

  public void startxmo()
  {
    string startfile = Dir + "\\xmo.exe";
    Process xmoappli = new Process();

    if (File.Exists(startfile))
    {
        xmoappli.StartInfo.FileName = startfile;
        xmoappli.Start();
    }
    else
    {
        MessageBox.Show("XMO.exe blev ikke fundet på den valgte lokation!");
        File.Delete(dir + "\\xmo.ini");
        dialog();
    }
  }
}

and then use for example Autofac, Simple Injector or some other kind of DI framework to inject the Kunde object into the form.

In essence, you are looking for a simple implementation of an observer pattern, where Kunde object observes the Main form, simple in the way which does not require dynamic registration or unregistration, so you can fix the dependencies via constructor injection.

Upvotes: 1

Ron16
Ron16

Reputation: 473

Where are you creating the instance of Kunde.cs form ? Perhaps you could pass dir through the parameters of a custom custructor for kunde.cs; Something a bit like (though it's a code from a slightly different context, but it uses the same style nonetheless.) -

private void button_login(object sender, EventArgs e)
{
   MainMenu ss= new MainMenu(textBox1.Text);
   this.Hide();            
   ss.Show();
}

class MainMenu : Form
{
    // This is an "Auto-Implemented Property".
    // Auto-Implemented Properties are used as a shortcut of what you have done.
    // Google them for more information.
    public string UserName { get; set; }

    private void MainMenu(string userName)
    {
        this.UserName = userName;
    }
}

Upvotes: 2

bogzy
bogzy

Reputation: 126

You can try creating a public class with parameter on form 2 (Kunde.cs) and insert the code you are call into that class. Call that function from main form and pass the parameter. For example:

//this should be on 2nd form
public void sampleFunction (string dir)
{
   //paste your code here
}

//this is how you will call it on main form
form2.sampleFunction(dir);

Upvotes: 1

Related Questions