Click here to Skip to main content
15,920,438 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hello, i try to create a list that displays a simple listbox with employees (medewerkers), however i receive the error:

CS0120 An object reference is required for the non-static field, method, or property 'Verzamel.GetAllMedewerkers(string)'

C#
<public void LoadMedewerkers()
        {
           
           lblMedewerkers.Items.Clear();

          
            string filter = "";
            List<medewerkers> medewerkers = Verzamel.GetAllMedewerkers(filter);

            
            foreach (Medewerkers s in medewerkers)
            {
                lblMedewerkers.Items.Add(s);
            }
        }


Verzamel.GetAllMedewerkers is referenced to this class:

C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Configuration;
using System.Data.SqlClient;
using System.Windows.Forms;

namespace TimeReg
{
    class Verzamel
    {

        private static string connectionString = ConfigurationManager.ConnectionStrings["TimeReg.Properties.Settings.TimeRegConnectionString"].ConnectionString;
        private SqlConnection conn = new SqlConnection(connectionString);

        
        List<medewerkers> medewerkers = new List<medewerkers>();
                

       public List<medewerkers> GetAllMedewerkers(string filter)
        {

            medewerkers = new List<medewerkers>();


            string query = "SELECT M.* FROM Medewerkers M";
                       
            if (filter != "")
            {
                query += " WHERE Voornaam LIKE '%" + filter + "%' OR Achternaam LIKE '%" + filter + "%'";
            }

 
            conn.Open();
            SqlCommand cmd = new SqlCommand(query, conn);


            using (SqlDataReader reader = cmd.ExecuteReader())
            {
                while (reader.Read())
                {

                    Medewerkers Medewerker = new Medewerkers();

              
                    Medewerker.Personeelsnummer = reader.GetInt32(0);
                    Medewerker.LoginID = reader.GetInt32(1);
                    Medewerker.Voornaam = reader.GetString(2);
                    Medewerker.Tussenvoegsel = reader.GetString(3);
                    Medewerker.Achternaam = reader.GetString(4);

                   
                    medewerkers.Add(Medewerker);
                }
            }

            conn.Close();
            return medewerkers;
        }
    }
}


What I have tried:

How can i fix this, i did try to add change the list to static, but it does not seems to work.

What do i need to do?

Any help is appriciated.

Thanks in advance.
Posted
Updated 31-May-18 7:34am
v2

The function Verzamel.GetAllMedewerkers(string filter) is not a static function. So you need an instance of the Verzamel class to call that function:
C#
// Create an instance of the Verzamel class 
//  (or use an already existing instance)
//Verzamel verz;
Verzamel verz = new Verzamel();
// Use the instance to call a member function
List<medewerkers> medewerkers = verz.GetAllMedewerkers(filter);
Alternatively make the function static. Then you can call it as before.
[EDIT]
public static List<medewerkers> GetAllMedewerkers(string filter)
{
    // Must use a local variable instead of the class member when
    //  this method is static and the member variable is not static
    List<medewerkers> medewerkers = new List<medewerkers>();

    // Similar for conn but not for connectionString which is static
    SqlConnection conn = new SqlConnection(connectionString);

    // ...
    return medewerkers;
}
[/EDIT]
[EDIT2]
Your function returns also always an empty list because you are creating a new list inside a loop and adding data to that. At the end of each loop iteration, that local list goes out of scope and is deleted. As a result, the member variable is still empty:
C#
while (reader.Read())
{
    // DELETE THIS!
    //Medewerkers Medewerker = new Medewerkers();
                  
    // ...
    
    medewerkers.Add(Medewerker);
}
[/EDIT2]
 
Share this answer
 
v5
Comments
Richard Deeming 31-May-18 13:35pm    
"... you are creating a new list inside a loop and adding data to that ..."

Are you sure about that? :)
Jochen Arndt 1-Jun-18 2:54am    
You are right.

Such can be overseen when same name is used for multiple variables with just different cases.

It was just a try to answer his problems posted as solved solutions.

Should have stuck to the answer of the initial question.
Quote:
This is an error that says objectreference is not on an object, i get this on the

This is one of the most common problems we get asked, and it's also the one we are least equipped to answer, but you are most equipped to answer yourself.

Let me just explain what the error means: You have tried to use a variable, property, or a method return value but it contains null - which means that there is no instance of a class in the variable.
It's a bit like a pocket: you have a pocket in your shirt, which you use to hold a pen. If you reach into the pocket and find there isn't a pen there, you can't sign your name on a piece of paper - and you will get very funny looks if you try! The empty pocket is giving you a null value (no pen here!) so you can't do anything that you would normally do once you retrieved your pen. Why is it empty? That's the question - it may be that you forgot to pick up your pen when you left the house this morning, or possibly you left the pen in the pocket of yesterdays shirt when you took it off last night.

We can't tell, because we weren't there, and even more importantly, we can't even see your shirt, much less what is in the pocket!

Back to computers, and you have done the same thing, somehow - and we can't see your code, much less run it and find out what contains null when it shouldn't.
But you can - and Visual Studio will help you here. Run your program in the debugger and when it fails, VS will show you the line it found the problem on. You can then start looking at the various parts of it to see what value is null and start looking back through your code to find out why. So put a breakpoint at the beginning of the method containing the error line, and run your program from the start again. This time, VS will stop before the error, and let you examine what is going on by stepping through the code looking at your values.

But we can't do that - we don't have your code, we don't know how to use it if we did have it, we don't have your data. So try it - and see how much information you can find out!
 
Share this answer
 
Start by fixing the SQL Injection[^] vulnerability in your code.

If you want to invoke the method using the class name, rather than an instance of the class, then the method needs to be static.

You won't be able to access the instance fields conn and medewerkers from a static method. You could just make those members static as well, but that would lead to problems if multiple threads called your method at the same time. Instead, since they're only used within the method, make them local variables.

Since everything in the class is now static, you can mark the class itself as static. This will prevent you from accidentally adding instance members to it.

You should avoid using SELECT * FROM ...; instead, you should explicitly list the columns you want to load. I've assumed that the column names match the property names on your class.
C#
static class Verzamel
{
    private static readonly string connectionString = ConfigurationManager.ConnectionStrings["TimeReg.Properties.Settings.TimeRegConnectionString"].ConnectionString;
    
    public static List<Medewerkers> GetAllMedewerkers(string filter)
    {
        List<Medewerkers> medewerkers = new List<Medewerkers>();
        
        using (SqlConnection conn = new SqlConnection(connectionString))
        using (SqlCommand cmd = new SqlCommand("", conn))
        {
            string query = "SELECT M.Personeelsnummer, M.LoginID, M.Voornaam, M.Tussenvoegsel, M.Achternaam FROM Medewerkers M";
            
            if (!string.IsNullOrEmpty(filter))
            {
                query += " WHERE M.Voornaam LIKE @filter OR M.Achternaam LIKE @filter";
                cmd.Parameters.AddWithValue("@filter", "%" + filter + "%");
            }
            
            cmd.CommandText = query;
            
            conn.Open();
            using (SqlDataReader reader = cmd.ExecuteReader())
            {
                while (reader.Read())
                {
                    medewerkers.Add(new Medewerkers
                    {
                        Personeelsnummer = reader.GetInt32(0),
                        LoginID = reader.GetInt32(1),
                        Voornaam = reader.GetString(2),
                        Tussenvoegsel = reader.GetString(3),
                        Achternaam = reader.GetString(4),
                    });
                }
            }
        }
        
        return medewerkers;
    }
}


Everything you wanted to know about SQL injection (but were afraid to ask) | Troy Hunt[^]
How can I explain SQL injection without technical jargon? | Information Security Stack Exchange[^]
Query Parameterization Cheat Sheet | OWASP[^]
 
Share this answer
 
I was to early

Now i get an error:

System.NullReferenceException
  HResult=0x80004003
  Message=De objectverwijzing is niet op een exemplaar van een object ingesteld.
  Source=TimeReg
  StackTrace:
   at TimeReg.Medewerker.LoadMedewerkers() in 
\source\repos\TimeReg\Medewerker.cs:line 33
   at TimeReg.Medewerker..ctor() in 
\source\repos\TimeReg\Medewerker.cs:line 22
   at TimeReg.Form1.button3_Click(Object sender, EventArgs e) in \source\repos\TimeReg\Form1.cs:line 201
   at System.Windows.Forms.Control.OnClick(EventArgs e)
   at System.Windows.Forms.Button.OnClick(EventArgs e)
   at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
   at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
   at System.Windows.Forms.Control.WndProc(Message& m)
   at System.Windows.Forms.ButtonBase.WndProc(Message& m)
   at System.Windows.Forms.Button.WndProc(Message& m)
   at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
   at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
   at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
   at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
   at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData)
   at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
   at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
   at System.Windows.Forms.Application.Run(Form mainForm)
   at TimeReg.Program.Main() in 


This is an error that says objectreference is not on an object, i get this on the

List<medewerkers> medewerkers = Verzamel.GetAllMedewerkers(filter);
 
Share this answer
 
v2
Comments
Jinto Jacob 30-May-18 8:07am    
please don't put your error as a solution for the question. Here you provided error explanation as an answer and accepted it. It will now show as resolved question. if you have to provide such information put it as comment or edit your question to add data

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900