简体   繁体   中英

C# public class error object reference not set to an instance of an object

I have the data being pulled from a separate c# file called data. The class for data is Version. I used a separate class to make my Label class. When I compile it, I get the, Object reference not set to an instance of an object. I am not sure why the error is happening. Since it is tied to a database.

public Data Version { get; set; }
    public Label Label { get; set; }

    public Form1()
    {
        InitializeComponent();

        CmboBoxLabel.Items.Add(new Label(Version.LabelName, Version.LabelCode));
    }

If you want any of the class code let me know.

Data Version Class

public class Data
{
    public Data()
    {
        LabelName = "";
        LabelCode = -1;
        LabelStock = -1;

    }

    public string LabelName { get; set; }
    public Int32 LabelCode { get; set; }
    public Int32 LabelStock { get; set; }

    public ODSData_XXXXX.TrayLabelReferenceRow toDataRow()
    {
        ODSData_XXXX.TrayLabelReferenceRow row = null;
        row.LabelName = this.LabelName;
        row.LabelCode = this.LabelCode;
        row.LabelStock = this.LabelStock;
        return row;
    }

    public static Data loadFromDataRow(ODSData_XXXX.TrayLabelReferenceRow row)
    {
        Data Version = new Data();
        Version.LabelName = row.LabelName;
        Version.LabelCode = row.LabelCode;
        Version.LabelStock = row.LabelStock;

        return Version;
    }
}

You're not instantiating Version anywhere in the scope of where you're wanting to use the variable. Do something like this:

public Label Label;

public Form1()
{
    Data version = new Data(); // this creates and instantiates a new Data object named Version
    InitializeComponent();

    CmboBoxLabel.Items.Add(new Label(version.LabelName, version.LabelCode));
}

Of course, after you create the version , you'll need to populate it's properties however you would like. Ultimately, you'll want to look more into Classes and Properties and how they work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM