Search code examples
c#crashvoid

SelectedIndex returns -1 in void/static void function


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


Solution

  • 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.