Home > Back-end >  SelectedIndex returns -1 in void/static void function
SelectedIndex returns -1 in void/static void function

Time:11-19

I have a problem with the combobox.SelectedIndex function. The problem is that in void and static void it just returns a -1. Now before anyone comes and says if there is anything in it at all, yes it is, I've debugged the code and found that it only returns a -1 in static void and void , now I'm curious as to why it doesn't work, actually a very simple code.

        void writecombo()
        {
            int CURRENT_LOG = combo.SelectedIndex; //< -1 
            Globals.LG[CURRENT_LOG]  = "Hello!"   Environment.NewLine; //Crash, because it is -1
            ...
        }

Where it works:

        private void textbox1_KeyDown(object sender, KeyEventArgs e)
        {
            if (GetAsyncKeyState(Keys.Enter) < 0)
            {
                int CURRENT_LOG = combo.SelectedIndex; // Not Null
                Globals.LG[CURRENT_LOG]  = "Hello!"   Environment.NewLine;
                ...
            }
        }

I would be happy to get help and also if someone could explain to me why this is the case :)

EDIT: The problem only comes when I want to access this void from a static void, I wanted to use it to access the objects in form1 in a static. (var from = new Form1) MRE

CodePudding user response:

void vs static void isn't exactly your problem. It's a static member trying to access the non-static members of its class. That barrier cannot be crossed.

When a member is static, there's only one instance of it, and it's attached to the class; it can only access members of the class that are also marked with the static keyword.

Members that are not marked static can access all the members of the class, including its static members. Each object you create from the class using new essentially gets its own copy of the non-static members.

In your code sample, you're trying to access a non-static member from a static member, and the runtime is telling you that can't be done.

CodePudding user response:

First of all, thanks to everyone tried to help me. It seems like accessing/calling an static function, to access with that the Form1 contents is a complicated and hard thing to do.

So, i found another way, instead trying to call a function, i am going to use a timer to check a global boolean value, if it is true, it should execute the code, very simple, it's not good, but at least a way to deal with it.

Still, i am opend for answers if anyone found a good and easy way to access the contents of a form with a static function in it.

  • Related