S. M.
S. M.

Reputation: 227

How to use (private) variable from a different function?

For full context, I'm working on WinForms, and firstly, I have a form that displays all the virtual machines I have on my Hyper-V Manager, with many functions associated to each button that makes changes to this datagridview. Here's how it looks like:

enter image description here

(ignore the names, they're all test machines)

So then there's that little blue button on the right that reads "Snapshot VM", and it opens a new form so you can pick a name for it, which looks like this:

enter image description here

What I want is to save the index that's selected on the main form (the row you clicked on before clicking the button) so I can call the function snapshotVM from my DLL, which looks like this:

public void snapshotVM(string id, string name)
        {
            if (name == "") powershellFunc("Get-VM | Where { $_.Id –eq ‘" + id + "’ } | Checkpoint-VM");
            else powershellFunc("Get-VM | Where { $_.Id –eq ‘" + id + "’ } | Checkpoint-VM -SnapshotName '" + name + "'");
        }

(powershellFunc just takes powershell commands and executes them, for clarification)

So basically I need to get the string id from one form, and the string name from another, or inside the same form get a private variable from one function and use it in another. Here's what I mean:

enter image description here

I need to use the index variable inside the button below. Is there any way to "transfer" it to there?

Finally, where should I call the snapshotVM function from, if I should at all, or is there any workaround this? Any help would be appreciated, including asking for clarification because I feel this is a bit of a mess and I haven't explained correctly, but I'll await suggestions for edits.

Upvotes: 0

Views: 55

Answers (1)

Michał Turczyn
Michał Turczyn

Reputation: 37430

Just use private variable on the class:

private string _index;
....
public NewSnapshotVM(...)
{
  ...
  _index = dgv.Rows[...];
}
...
pirvate void button1_Click(...)
{
  // use _index as much as you want
}

Upvotes: 2

Related Questions