Bob Jones
Bob Jones

Reputation: 23

Object reference not set to an instance error

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;


    }

Upvotes: 1

Views: 4834

Answers (3)

Aswin
Aswin

Reputation: 1

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());

Upvotes: 0

Lander
Lander

Reputation: 3437

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);

}

Upvotes: 4

jammykam
jammykam

Reputation: 17000

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();

Upvotes: 3

Related Questions