Hi! I'm new to the site! I've been searching for help on Google for a while and keep getting results that point to this site, so I figured I should jump on.

I'm new to C#. I've been programming in VBA in MS Access for a while now and have a solution that is running effectively where I work. (had to brag about that for a second :) ) But I just started with C# though. VBA is okay, but it is (to me) a little limiting.

I've decided as my first learning tutorial to teach myself how to create a custom file type, store user settings and data in it and then retrieve it later. The first problem I have run into is how to correctly save data and retrieve it.

I have a form that I created thus far, on that form is a menu bar and a text box. I have successfully exported (in binary) the data typed into the box, and then successfully retrieved it. My question is...what if I have two text boxes? What about 30?

I'd love to get some help and some suggestions on this. Code is nice if you feel up to it, but remember VB is my only real experience so comment any code up so I know what's going on...I'm not big on "ohhh! code! [copy/paste]" I like to know what every line does and why. I'll probably be learning C# for years because of that though.

Anyway, I'll dig up my code and paste it for you guys but it might take a while...I'm at work right now and my source code is at home.

I guess the summary of all this is....if I want to create a file that holds all settings, all data and any future data...is serialization the way to go? If your familiar with Intuit's Quickbooks...think of the "company file." I need something that can save info, but can't be easily compromised by someone opening a binary file in notepad and retrieving a username or password.

ddanbe commented: Nice question! +5

Recommended Answers

All 55 Replies

Have a look at using XML files for settings and the like.

I would, except that XML is human readable. Anyone can open a xml file and even with no experience can stumble through it and extract data that they shouldn't have access to. I just don't think XML will work. Maybe I'm wrong? How secure is data stored in XML files?

You can use a serialiser to write whole objects (including state) to a file. If you write to binary it is not human readable as far as i know. Some things like property names are written, but the rest is usally random symbols. If you are concerned about security you can look into encryption.
If you go down the serialiser route then i'd suggest writing a class to store all of your settings in, implement ISerializable and you can write the whole calss to a binary file. Check out this, it helped me get my head around serializers.

You can use a serialiser to write whole objects (including state) to a file. If you write to binary it is not human readable as far as i know. Some things like property names are written, but the rest is usally random symbols. If you are concerned about security you can look into encryption.
If you go down the serialiser route then i'd suggest writing a class to store all of your settings in, implement ISerializable and you can write the whole calss to a binary file. Check out this, it helped me get my head around serializers.

Thanks! I've seen that site before but never paid much attention to it. I'll check into it again. Thanks!

You can use a serialiser to write whole objects (including state) to a file. If you write to binary it is not human readable as far as i know. Some things like property names are written, but the rest is usally random symbols. If you are concerned about security you can look into encryption.
If you go down the serialiser route then i'd suggest writing a class to store all of your settings in, implement ISerializable and you can write the whole calss to a binary file. Check out this, it helped me get my head around serializers.

Would you, or someone else be able to help explain what is going on in some of the code? I'm sure the code works, but like I said, I'm not a big cut/paste kinda guy. The tutorial was written well, and I think I understand what is happening, but I have some questions about the syntax. For example, this section of code:

public class ObjectToSerialize
{
   private List<Car> cars;

   public List<Car> Cars
   {
      get { return this.cars; }
      set { this.cars = value; }
   }

   public ObjectToSerialize()
   {
   }
}

what is going on in:

private List<Car> cars

"List<Car> cars" is pretty much my question...I've never seen something like that before. (again I'm a VBA user, so maybe it's not in VBA)...

This is a concept you will want to familiarise yourself with. A List is a strongly typed collection. So List<Car> is declaring a collection that will store objects of the type Car. In the example he has a class called Car. The List will store instances of that class. The basics of using lists are as follows:

private void ListPlay()
        {
            //im using a list of integers
            List<int> intList = new List<int>();

            //add item to List
            intList.Add(1);
            intList.Add(2);

            //or instantiate object first
            int i = new int();
            i = 3;
            intList.Add(i);

            //sort list items
            //using default sort
            intList.Sort();
            //using custom sort 
            //(Comparison points to method that compares items to determine sort order)
            intList.Sort(new Comparison<int>(SortDesc));

            //find the first item matching variable i using an inline delegate
            intList.Find(delegate(int item) { return item == i; });


            //remove items from list

            //by object
            intList.Remove(i);
            //remove by index
            intList.RemoveAt(0);
            //remove all
            intList.RemoveAll();
        }

        private int SortDesc(int int1, int int2)
        {
            //by compare int2 to int1 instead of int1 to int2 
            //the numbers are ordered from largest to smallest
            return int2.CompareTo(int1);
        }

A list is similar to an array, except you dont have to determine its size when you instantiate it.

Props!

Thank you for that! I'll read over your explanation properly at my lunch break in a few minutes.

I think I see what is going on though. Thank you so much for taking the time to explain that to me! I'll take a closer look in a few and if I have any other questions I'll let you know. I really do appreciate your help!

I'm heading away for the weekend so i'll probably not be on until Tuesday. I'll check in if i can, but i'm sure the other solvers can help if you have more questions.
Lists are a very powerful tool once you get the hang of them so its worth reading up. What i gave you was just a few of the ways you can use them. The Sort and Find methods are the trickier ones to understand as they involve predicates and delegates which take some getting used to :)

Good luck

I'm heading away for the weekend so i'll probably not be on until Tuesday. I'll check in if i can, but i'm sure the other solvers can help if you have more questions.
Lists are a very powerful tool once you get the hang of them so its worth reading up. What i gave you was just a few of the ways you can use them. The Sort and Find methods are the trickier ones to understand as they involve predicates and delegates which take some getting used to :)

Good luck

That's okay! I'm pretty independent when it comes to learning stuff, but I need a base and you have definitely helped get that going. I'm going to the library tonight to get a book on C#...hopefully I can find one.

I do have an additional follow up question for clarification.

Because I'm used to VBA, I think I'm having some trouble wrapping my brain around how the basics of C# work...let me ask this and tell me if I am correct in my logic here:

In VBA we have functions and subroutines...when either of them complete, the variables that were in memory are lost (I believe they are set to 0, or "nothing") So if I run a function once and i = 2, I cannot reference i anywhere else in a different function or subroutine and expect it to be the same as the i I had before. Obviously there are ways to pass that variable value around through recursion and calling other functions or subs within another...

But with C#...it seems like "objects," like in the car example called Car...is stored in memory while the program is running, even if a form is just sitting there open with no interaction from a user. Is that correct?

So, for example, if I have a button on a form and when someone clicks the button it sets a value of 1 to a variable called i. And there is a second button, that when clicked would display a message box saying the value of that i without first writing the value to a textbox control or something? that i value is "saved" in memory in an object that I define right?

The process of extracting the object that I created to hold my i value from the system's memory (RAM, not a HDD) and writing it to a file on the system's hard drive or floppy (if anyone even uses those anymore) is the serialization process right?

But in the case of C#, objects can hold multiple values, not just one and those objects and values can be serialized.

Is that correct?

pretty much, yes.
How persistant a variable is depends on its scope:

public Class ExampleClass
{
   public string ClassString = "something";

   public void Method1(string strInput)
   {
        string Method1String = "test";
        int i = Method3(Method1String);
   }

   public string Method2(string strInput)
   {
        string Method2String = strInput + ClassString;
        return Method2String;
   }

   public int Method3(string strInput)
   {
        return strInput.Length;
   }

}

The variable declared in the Class (ClassString) is a class level variable (called a field) and is accesible to any method within the class, the same way that the methods themselves are accesible throughout the class. I'll ignore public and private for now, but you should look into those too :)

A method declared as void has no return value, otherwise the it should return a value of the type declared..Method1 has no return value, Method3 returns an integer.

A variable declared within a method only exists within the method and will be disposed of when the method exits. So Method2String only exists whilst Method2 is being executed. And Method3 is never aware that Method2String exists.

The way that List<Car> works is that the List is declared as a field so it persists for as long as the instance of the Class exists. So you would usually have a main Form (which is itself an instance of the Form Class) which is the basis for your program and remains in existance until the program closes. This form will host any objects that you need to maintain in memory. Inside that form you would instantiate a List, then add to it instances Car class.
Each instance of the Car class remains in memory for as long as the List exists, the List exists for as long as the Form exists.

Sorry if this has been confusing, it's hard to know the best way to explain it without knowing what concepts you are already comfortable with. If you are happy learning on your own i would suggest you read up around Classes and Objects, Access Modifiers, Fields Methods and Members, Value/Reference types and Static members.

Its a long list but a lot of it is related and you will need a firm grasp on those subjects if your to be a confident coder :)
The msd pages are often a good place to start.

commented: Very, very helpful! Thank you! +1

I apparently wrote this while Ryshad was replying. He covers most of it in a more elegant fashion, but I'll post it anyway.

Local variables work like you mentioned your i did in VBA. If you declare it in a function, it goes out of scope when the function ends and is no longer available.

In C# as long as someone still has a reference to an object (or list or other collection of objects) the objects continue to persist.

If the form references a car, the form can continue to refer to that same car as long as the form exists. (Even if the user is not interacting with the form at the time.)

Regarding your form and button question, as long as the two components reference i in the same way relative to the form, they would be working with the same value.

Yes, the process of extracting data from an object in memory and writing it to an output (sometimes a file, but could be something else) is what serialization is.

The "objects can hold multiple values" is somewhat incorrect. I think what you're confused with is that there may be more than one instance of an object.

If Car is a class, then Car myCar = new Car(); declares an instance of a car that I called "myCar". I could then additionally declare Car yourCar = new Car(); . Than made 2 different, but similar 'cars'. Each car has its own data. There can be several instances of the Car class with different data values, but each Car instance only has one value for each data item.

Sorry if this has been confusing, it's hard to know the best way to explain it without knowing what concepts you are already comfortable with. If you are happy learning on your own i would suggest you read up around Classes and Objects, Access Modifiers, Fields Methods and Members, Value/Reference types and Static members.

Its a long list but a lot of it is related and you will need a firm grasp on those subjects if your to be a confident coder :)
The msd pages are often a good place to start.

No actually, that wasn't confusing at all really. That was very helpful! I'm starting to get the general idea. I'll go to the library today and see what I can find. Do you recommend any particular books? I was just going to check out whatever I could find...programming books, even in the big libraries in St. Louis, are hard to find...at least any that are up to date.

I apparently wrote this while Ryshad was replying. He covers most of it in a more elegant fashion, but I'll post it anyway.

Local variables work like you mentioned your i did in VBA. If you declare it in a function, it goes out of scope when the function ends and is no longer available.

In C# as long as someone still has a reference to an object (or list or other collection of objects) the objects continue to persist.

If the form references a car, the form can continue to refer to that same car as long as the form exists. (Even if the user is not interacting with the form at the time.)

Regarding your form and button question, as long as the two components reference i in the same way relative to the form, they would be working with the same value.

Yes, the process of extracting data from an object in memory and writing it to an output (sometimes a file, but could be something else) is what serialization is.

The "objects can hold multiple values" is somewhat incorrect. I think what you're confused with is that there may be more than one instance of an object.

If Car is a class, then Car myCar = new Car(); declares an instance of a car that I called "myCar". I could then additionally declare Car yourCar = new Car(); . Than made 2 different, but similar 'cars'. Each car has its own data. There can be several instances of the Car class with different data values, but each Car instance only has one value for each data item.

Hmmmm...so if I was talking to a kid and wanted to explain objects to him I could say: these video game boxes are instances of a class (they are all boxes with the same size, color etc...they are identical), but, each box contains a different video game inside it.

Right? I know...childish example, but still...

Yes that would be a valid example.

Another example would be a 'person' class. Each person has attributes: name, address, phone number, birthday, ...

But any two instances of 'person' are different.

Yes that would be a valid example.

Another example would be a 'person' class. Each person has attributes: name, address, phone number, birthday, ...

But any two instances of 'person' are different.

Ok, then here is my next question.

Can variables cross classes?

In the example that Ryshad gave, Method3 has no idea that Method2String exists. Does that apply to Classes? Like If I have a public class called class1 and some class strings defined there called class1string and class1string2 can a different class called class2 use the data in class1string?

I guess if I have any variables that need to persist in memory I need to declare them on the class level and keep the form that hosts the class open right?

Now we're getting into scope a bit (and its a big topic) but class-level variables only exist once, regardless of the number of instances of the class.

Based on your example, where you want something to persist, it could be a regular member of a class instance and the form could keep that instance around as long as the form was open, it wouldn't have to be a class-level data item. Depending on the data you want to persist, the form could just have the data instead of another class (forms are usually classes too) if that would be more convenient.

class1 and class2 normally don't have any idea that the other class exists unless they need to use the class for something. That is normally a GOOD thing. It encourages and promotes modularity in the code.

If it was necessary, class2 could access the string inside class1 if the string was declared as a public member of the class. Then class2 could reference the string via something like class1::class1string . I would personally however tend to discourage it. If you have an example where you think it might be appropriate, describe it and we'll evaluate whether or not that's a valid application and discuss alternatives.

Now we're getting into scope a bit (and its a big topic) but class-level variables only exist once, regardless of the number of instances of the class.

Based on your example, where you want something to persist, it could be a regular member of a class instance and the form could keep that instance around as long as the form was open, it wouldn't have to be a class-level data item. Depending on the data you want to persist, the form could just have the data instead of another class (forms are usually classes too) if that would be more convenient.

class1 and class2 normally don't have any idea that the other class exists unless they need to use the class for something. That is normally a GOOD thing. It encourages and promotes modularity in the code.

If it was necessary, class2 could access the string inside class1 if the string was declared as a public member of the class. Then class2 could reference the string via something like class1::class1string . I would personally however tend to discourage it. If you have an example where you think it might be appropriate, describe it and we'll evaluate whether or not that's a valid application and discuss alternatives.

True, allowing modularity is definitely a good thing now that I think about it a bit more.

I guess the instance I am thinking of (and I might be still thinking on the VBA level) is a situation where saved settings are used.

I couldn't write the code for the life of me so I'll just describe it and maybe play with it tonight and see what I can do. But for example, if I have a main form...call it form1 and there is a menu option called session settings or something, and when you click it, form2 opens showing all of the options that are available at the moment. If one of the options in form2 disables a feature or switches something on or off on form1, wouldn't variables crossing over forms be a situation where classes should share variables? Especially if form1 needs to know the value of a variable that is altered by form2 so it can use it later.

To be more specific, let's say my main form has a menu bar and a toolbar, if I open my settings form (form2) and check a box that is supposed to hide the toolbar and when I click OK it does just that...wouldn't I need to set a variable on form1 to reflect that change? Especially if when the user exits the program, that setting is saved to a preferences file or something?

If you have an example where you think it might be appropriate, describe it and we'll evaluate whether or not that's a valid application and discuss alternatives.

Here is a perfect example that I have run into. I need to get the text from a textbox in a form so that when i click the file menu in the parent form and click save it will serialize and write the data to the disk that is in the editor window.

Here is my code...I can't figure this out. :confused:

frmMain (This is the parent window)

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

namespace Binary_Text_Editor
{
    public partial class frmMain : Form
    {
        private String serializeme;

        serializeme = frmEditor.editorbodytext();

        public frmMain()
        {
            InitializeComponent();
        }

        private void saveToolStripMenuItem_Click(object sender, EventArgs e)
        {
            
            BinaryFormatter binaryFormat = new BinaryFormatter();
            Stream fStream = new FileStream("Data.dat",
            FileMode.Create, FileAccess.Write, FileShare.None);
            binaryFormat.Serialize(fStream, serializeme);
            fStream.Close();
        }

        private void openToolStripMenuItem_Click(object sender, EventArgs e)
        {
            BinaryFormatter binaryFormat = new BinaryFormatter();   
            Stream fStream = File.OpenRead("Data.dat");
            serializeme = (string)binaryFormat.Deserialize(fStream);

        }

        private void newToolStripMenuItem_Click(object sender, EventArgs e)
        {
            frmEditor editor = new frmEditor();
            editor.Show();
            editor.MdiParent = this;
        }

        private void quitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void optionsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            frmOptions options = new frmOptions();
            options.Show();
            options.MdiParent = this;
        }
    }
}

frmEditor (this is the editor window)

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

namespace Binary_Text_Editor
{
    public partial class frmEditor : Form
    {
        public frmEditor()
        {
            InitializeComponent();
        }
        private String _editorbody;

        public String editorbodytext
        {
            get { return _editorbody; }
        }
    }
}

I attached the project as well...

The error is being thrown on line 18. The errors are:

Error 1 Invalid token '=' in class, struct, or interface member declaration C:\Users\Webers\Documents\Visual Studio 2008\Projects\Binary Text Editor\Binary Text Editor\frmMain.cs 18 21 Binary Text Editor

Error 2 Invalid token '(' in class, struct, or interface member declaration C:\Users\Webers\Documents\Visual Studio 2008\Projects\Binary Text Editor\Binary Text Editor\frmMain.cs 18 47 Binary Text Editor

I didn't download or open your project (FYI)

I believe that your compiler error on line 18 is related to you attempting to set a member variable in a class scope, and because the thing you are setting it to (if it even resolves) is a property of an object instance that you reference through the class name.

I believe there are a couple of 'normal' ways to access data that will be updated in child forms. One way would be to pass a communication structure (that the parent owns or also references) for the child form to update (as appropriate -- usually when the user clicks OK). A second way would be for the parent form to keep the reference to the child form (from when it creates the child form) and use that reference to access the child forms data.

In your project example, I would probably have the parent form keep a reference to the open editor frame.

NOTE: You don't want to make the private string serializeme and initialize it from the child frame. It would only get the initial value. You need to ask the editor frame for the current contents when the save strip tool menu item is selected. When the open strip tool menu item is selected, you need to make the editor frame (if it does not already exist) and then tell it to update its contents from what you read. The current implementation where it sets the value of serializeme would never update the child form.

I didn't download or open your project (FYI)

I believe that your compiler error on line 18 is related to you attempting to set a member variable in a class scope, and because the thing you are setting it to (if it even resolves) is a property of an object instance that you reference through the class name.

I believe there are a couple of 'normal' ways to access data that will be updated in child forms. One way would be to pass a communication structure (that the parent owns or also references) for the child form to update (as appropriate -- usually when the user clicks OK). A second way would be for the parent form to keep the reference to the child form (from when it creates the child form) and use that reference to access the child forms data.

In your project example, I would probably have the parent form keep a reference to the open editor frame.

NOTE: You don't want to make the private string serializeme and initialize it from the child frame. It would only get the initial value. You need to ask the editor frame for the current contents when the save strip tool menu item is selected. When the open strip tool menu item is selected, you need to make the editor frame (if it does not already exist) and then tell it to update its contents from what you read. The current implementation where it sets the value of serializeme would never update the child form.

OK, let me play with it some more and then I'll repost what happens...*crosses fingers* this isn't that complicated of a task either....but I'm determined!

I will try and help there are some quite fundamental points that you cover.

In object oriented programming a class defines an instance of an object e.g.
A class 'Car' may define this: A car is a vehicle that has four wheels an engine and a steering wheel, it can move forwads and backwards, you can steer it from side to side and it can be stopped. An instance of this class 'Car' would be my car parked on the driveway, my wifes car or any car I have ever seen apart from Del Boys Robin Reliant as that has three wheels.

When you create an instance of (instantiate) an object, that object is put in memory and any public elements can be accessed through it, any private elements cannot. Whether or not a variable is kept in memory depends on the scope of the variable. When I say scope of a variable I am refering to when it is declared, like in VBA when a variable is declared inside a method you can only access it within that method. If a varialble is declared at the top level of a class it is known as a member variable and is available for the lifetime of an instance, the moment that instance is disposed or goes out of scope it will no longer be possible to reference it.

public class MyClass
{
   public float PublicProperty{ get; set; }

   public string PublicMemberVariable;

   private int _privateMemberVar;

    public MyClass()
    {
          int count = 0; // count becomes avaialable here
          
          for(int index=0;index < 10;index++)
          {
                    
          }
          // index is nolonger available  
        
    }// count is no longer available


}

I will try and help there are some quite fundamental points that you cover.

In object oriented programming a class defines an instance of an object e.g.
A class 'Car' may define this: A car is a vehicle that has four wheels an engine and a steering wheel, it can move forwads and backwards, you can steer it from side to side and it can be stopped. An instance of this class 'Car' would be my car parked on the driveway, my wifes car or any car I have ever seen apart from Del Boys Robin Reliant as that has three wheels.

When you create an instance of (instantiate) an object, that object is put in memory and any public elements can be accessed through it, any private elements cannot. Whether or not a variable is kept in memory depends on the scope of the variable. When I say scope of a variable I am refering to when it is declared, like in VBA when a variable is declared inside a method you can only access it within that method. If a varialble is declared at the top level of a class it is known as a member variable and is available for the lifetime of an instance, the moment that instance is disposed or goes out of scope it will no longer be possible to reference it.

public class MyClass
{
   public float PublicProperty{ get; set; }

   public string PublicMemberVariable;

   private int _privateMemberVar;

    public MyClass()
    {
          int count = 0; // count becomes avaialable here
          
          for(int index=0;index < 10;index++)
          {
                    
          }
          // index is nolonger available  
        
    }// count is no longer available


}

I might be starting to understand this a bit better. But here's my question, and maybe I am just totally thinking of this wrong...

I understand what you explained about scope...I think. Your code example reinforces what I was thinking about the scope of variables, but, as I was asking before, what about referencing variables from across forms?

Let me explain a bit better and maybe you can guide me in the right direction.

Right now my project consists of 2 forms (that I am using), the first form is a "container" it "holds" instances of the second form right? Okay, so the parent form (called frmMain) has a menu strip to open, close and save instances of the second form, called frmEditor.

Now, if I want to have a __________ (does class go here? its equivalent to a VBA function), that will serialize an instance of the second form (frmEditor). Now, my confusion is coming from this: the second form, frmEditor, contains only 1 thing on it, a multiline textbox. When I serialize the frmEditor, I want to save the text in that text box. This is where I am running into the problem. The main form, frmMain, that contains the menu strip that has the option to save, needs to be able to get the text in that box in order to save it, correct? How is that achieved? I've tried most everything that I can think of.

Do I need to serialize the entire frmEditor class? If so, how does the program know which one to serialize? The main form is a container and can have multiple instances of frmEditor running within it. Do I need to identify which one to serialize somehow? Do I assign an incrementing property to frmEditor when it opens so I can refer to it later?

Also, should the serialize function be on the frmMain form? or should I create a new class file and put it in there?

So many questions...but you guys have been so awesome at helping...I really do appreciate it! How do you have the patience? :)

For a multiple form interface, you will need to keep a list of all of the open forms and keep the list current when forms are closed or opened. You will also need a method to reference the 'current form', the one the user is currently interacting with.

When the user clicks save, you should save the data from the current form. (You might consider adding a 'save all' button that would iterate all of the forms saving each of them.) It also might be beneficial to have a 'dirty' flag that would let you know if the form had any changes to save. You could set the dirty flag any time a change is made to the text field.

Based on your described implementation, I think I would be tempted put the serialization in the child form. The main form would only call a method to tell the child it was time to save and the child would take care of getting it done.

For a multiple form interface, you will need to keep a list of all of the open forms and keep the list current when forms are closed or opened. You will also need a method to reference the 'current form', the one the user is currently interacting with.

When the user clicks save, you should save the data from the current form. (You might consider adding a 'save all' button that would iterate all of the forms saving each of them.) It also might be beneficial to have a 'dirty' flag that would let you know if the form had any changes to save. You could set the dirty flag any time a change is made to the text field.

Based on your described implementation, I think I would be tempted put the serialization in the child form. The main form would only call a method to tell the child it was time to save and the child would take care of getting it done.

Ok, so...on private void saveToolStripMenuItem_Click(object sender, EventArgs e) (Which is located on frmMain) i need to call a method located on frmEditor right? That method would serialize the form and save it...correct?

How do you call methods? Is it simply MyClass.Method(arguments); ? or would it be something like frmEditor.MyClass.Method(arguments); I'm assuming that when the menu option is clicked and the call is made to the child form that the serialization process would serialize the textbox and when that file is opened by deserializing, the text would be restored?

You generally call methods on an object instance. (This is why I was talking about 'keeping' a reference to the child windows you created and 'knowing' which child was the current one.) You would ask the current form to save.

// If you setup using a framework and setup your main window to support MDI
// you might be able to use this.ActiveMdiChild
// but it will be of type Form and not frmEditor
frmEditor currentEditor = this.activeEditor.
if (currentEditor != null)
    currentEditor.Method(arguments)
// If you setup using a framework and setup your main window to support MDI
// you might be able to use this.ActiveMdiChild
// but it will be of type Form and not frmEditor
frmEditor currentEditor = this.activeEditor.
if (currentEditor != null)
    currentEditor.Method(arguments)

That makes sense I suppose, but if it is a MDI container, and there is an active child window, when the user clicks the menu on the main form, does that make the child window lose focus? If it loses focus would using this.ActiveMdiChild work?

Also...I'm a little lost about why you would call a function in that way, it seems like you are doing it backwards... like...

frmEditor is the location of the method I want to run, so in order to run a method there I need to call the method by making a new object and then assigning that object a value that is never used anywhere? That's what it looks like you are doing. frmEditor currentEditor = this.activeEditor. so what is currentEditor and activeEditor? other than within the if statement where you reference currentEditor.method(), why would you bother doing frmEditor currentEditor = this.activeEditor. ...couldn't you just say frmEditor.method()...it seems to me that it would be the same? Maybe I'm thinking of it wrong?

That makes sense I suppose, but if it is a MDI container, and there is an active child window, when the user clicks the menu on the main form, does that make the child window lose focus? If it loses focus would using this.ActiveMdiChild work?

Also...I'm a little lost about why you would call a function in that way, it seems like you are doing it backwards... like...

frmEditor is the location of the method I want to run, so in order to run a method there I need to call the method by making a new object and then assigning that object a value that is never used anywhere? That's what it looks like you are doing. frmEditor currentEditor = this.activeEditor. so what is currentEditor and activeEditor? other than within the if statement where you reference currentEditor.method(), why would you bother doing frmEditor currentEditor = this.activeEditor. ...couldn't you just say frmEditor.method()...it seems to me that it would be the same? Maybe I'm thinking of it wrong?

Clicking on the menu or toolbar in an MDI parent does not change the MDIChild focus. (Note that it is tracking an MDI focus, the menu or tool bar might have the event focus, but the MDI child focus was not changed.)

You have to have an instance to call a method. If you have 3 editors open, which one would you mean if you say frmEditor.method() ?

The frmEditor currentEditor = this.activeEditor; makes a copy of a reference that the class was maintaining. It ensures that the reference is of the type we expect and will generate a compile error if the type of this.activeEditor cannot be converted to frmEditor.

Now that we have a particular instance of the form, we can call currentEditor.method() the compiler knows the type that currentEditor is and calls the appropriate method based on that type. (In this case, it will call frmEditor.method() with 'this' initialized to the object referred to by currentEditor.)

Clicking on the menu or toolbar in an MDI parent does not change the MDIChild focus. (Note that it is tracking an MDI focus, the menu or tool bar might have the event focus, but the MDI child focus was not changed.)

You have to have an instance to call a method. If you have 3 editors open, which one would you mean if you say frmEditor.method() ?

The frmEditor currentEditor = this.activeEditor; makes a copy of a reference that the class was maintaining. It ensures that the reference is of the type we expect and will generate a compile error if the type of this.activeEditor cannot be converted to frmEditor.

Now that we have a particular instance of the form, we can call currentEditor.method() the compiler knows the type that currentEditor is and calls the appropriate method based on that type. (In this case, it will call frmEditor.method() with 'this' initialized to the object referred to by currentEditor.)

Wait...should it be this.activeEditor or should it be this.ActiveMdiChild ?

doesn't activeEditor need to be defined first? like ... activeEditor = this.ActiveMdiChild ... see what I'm saying?

My original thought was that you would track the current editor as a frmEditor in your code. Upon further thought and contemplation (see reading the manual) I have revised my opinion.

We can use this.ActiveMdiChild but it is of type Form and not the class we want (frmEditor). We need to 'cast' it to our type so we can call our method (as our method is not defined in the Form class).

We can use the c# 'as' to make the conversion for us, without throwing an exception if the cast fails. (If the cast fails, as returns null.)

frmEditor currentEditor = this.ActiveMdiChild as frmEditor;
if (currentEditor != null)
    currentEditor.method(arguments);
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.