1

I can't figure out why this keeps happening. I'm a beginner but to me there is a reference set to an instance. I had trouble at first getting the class to have a size for the array which is now set to 100

Here is my code.

Form1.cs

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

namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{

    SalesmanClass[] salesmen = new SalesmanClass[100];


    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {

        if (textBox6.Text.Trim().Length != 0)
        {


            for (int i = 0; i <= salesmen.Length; i++)
            {

                if (salesmen[i] == null)
                {
                    salesmen[i].name = textBox6.Text; // error happens here when i enter something into the form it says
                    //Object reference not set to an instance of an object error
                    break;

                }

            }

        }
        else
        {
            MessageBox.Show("Please Input a Name");
        }

    }

    private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
    {

    }

    private void button2_Click(object sender, EventArgs e)
    {
        List<string> names = new List<string>();

        for (int i = 0; i < salesmen.Length; i++)//var salesmen in salesmen)
        {
            names.Add(salesmen[i].Name);// same problem here
        }
        listBox1.Items.Add(names);

    }

    private void textBox6_TextChanged(object sender, EventArgs e)
    {

    }

    private void button2_Click_1(object sender, EventArgs e)
    {

    }
}
}

SalesmanClass.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace WindowsFormsApplication1
{
public class SalesmanClass
{

    public string name;
    public string cNum;
    public string Email;
    public string address;
    public string gArea;
    public int tSales;

    public SalesmanClass()
    {
        name = null;
        cNum = null;
        Email = null;
        address = null;
        gArea = null;


    }
2
  • 1
    You don't need to declare your strings as null in the SalesmanClass() initializer, they are initialized as empty anyway. Also, just call it Salesman, we already know it is a Class from the declaration. Commented May 20, 2013 at 6:51
  • This question is similar to: What is a NullReferenceException, and how do I fix it?. If you believe it’s different, please edit the question, make it clear how it’s different and/or how the answers on that question are not helpful for your problem. Commented Jul 6, 2024 at 13:18

3 Answers 3

4

You use the == operator in your if statement, meaning that if the salesman IS null, set its name. I believe you meant that if the salesman is not null (!=). You're also going to encounter an index out of range exception in your for loop, so I've fixed that here as well.

for (int i = 0; i < salesmen.Length; i++)
{

    if (salesmen[i] != null)
    {
        salesmen[i].name = textBox6.Text; // error happens here when i enter something into the form it says
        //Object reference not set to an instance of an object error
        break;

    }

}

If you did mean for that instance to be null, perhaps you want something like this:

for (int i = 0; i < salesmen.Length; i++)
{

    if (salesmen[i] == null)
    {
        salesmen[i] = new SalesmanClass();
        salesmen[i].name = textBox6.Text; // error happens here when i enter something into the form it says
        //Object reference not set to an instance of an object error
        break;

    }

}

In your button2_Click method, you are encountering the same issue because you aren't skipping the null salesmen. You can also see that I commented that I changed the field which you are accessing from Name to name since in the class which you posted, there is no Name field.

private void button2_Click(object sender, EventArgs e)
{
    List<string> names = new List<string>();

    for (int i = 0; i < salesmen.Length; i++)//var salesmen in salesmen)
    {
        if (salesmen[i] != null)
        {
            names.Add(salesmen[i].name); // changed from .Name to .name
        }
    }
    listBox1.Items.Add(names);

}
Sign up to request clarification or add additional context in comments.

8 Comments

but if it is not null then it will pass over it, i want it to find a spot in the array that is null in the spot put what ever is in the textbox into salesmen[i].name
ah, okay, so i need to make a new object everytime.
@BobJones correct. You need to make a new object because initializing the array does not initialize any indexes in the array. It simply allocates an array with 100 free slots for salesmen.
im also getting the same error in button2_click method could you please take a look?
Use a list for salesmen like a suggested below, it will solve your button2 issue
|
3

Just remember that this line doesn't create any new SalesmanClass objects, only 100 references of type SalesmanClass.

SalesmanClass[] salesmen = new SalesmanClass[100];

I think you want:

if (salesmen[i] == null)
{
    salesmen[i] = new SalesmanClass();
    salesmen[i].name = textBox6.Text;
    break;
}

[EDIT] Lander beat me to it. What I would suggest is you use a List, the you don't have to worry about "empty spots"

List<Salesman>() salesmen = new List<Salesman>();

And then replace your for loop code with simply:

if (textBox6.Text.Trim().Length != 0)
{
    salesmen.Add(new Salesmane() { name = textBox6.Text } );
}
else
{
    MessageBox.Show("Please Input a Name");
}

You use this further down in List<string> names.

You might have to declare getters and setters on your properties:

public string Name { get; set; }

I would also make these property names CamelCase since that is the accepted standard.

You'll need to update your button2_click to use Count instead of Length or use a foreach loop:

foreach (Salesman salesman in salesmen)
{
names.Add(salesman.Name);
}

You can also use LINQ to simplify, this does exactly the same ting:

List<string> names = salesmen.Select(s => s.Name).ToList();

10 Comments

This should be the accepted answer as it teaches some better practices, and will speed up your code by not requiring you to iterate over your array to find a free index.
@jammykam if i changed it to a list would i be able to use listbox1.DataSource = salesmen;
Yes, you can use it in exactly the same. I very rarely use arrays, Lists are more robust. Thanks @Lander, you're kind.
@jammykam I'm a little confused with this, I need to get rid of SalesmanClass[] salesmen = new SalesmanClass[100]; and replace is with var salesmen = new List<Salesman>(); because one is an array and one is a list so I can't have both. When i try to make it a list, the compiler says that var may only appear within a local variable devlaration
Ahhh yes, I'll update the code, just declare it List<Salesman> salesmen = new List<Saleman>()
|
0

if an object reference error occurs check whether the variable u pass is correctly matching the correct index eg : If you are using Grid check whether the variable u access correctly pointing the index of the grid.

int StudID = 
Convert.ToInt32(editableItem.OwnerTableView.DataKeyValues[editableItem.ItemIndex]
["StudID"].ToString());

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.