سؤال

When running my program I am receiving a weird error that I've been trying to fix for a while now. Edited:

        DataTable peers = new DataTable();

        ObjectSerialisation.FileInit();

        if (ObjectSerialisation.PeerExists() && !(ObjectSerialisation.PeersEmpty()))
        {
            peers = ObjectSerialisation.DeserialisePeers();
        }
        else
        {
            peers.Columns.Add("nick");
            peers.Columns.Add("address");
            peers.Rows.Add("xnbya", "4lxi4nv5kkhyks2x.onion");
            peers.Rows.Add("curly", "h3m36rpq35rv7n36.onion");
            peers.PrimaryKey = new DataColumn[] { peers.Columns["address"] };
        }

        lstRecentChats.DataSource = peers;
        lstRecentChats.DisplayMember = "nick";

The lstRecentChats.DataSource = peers; always throws:

An unhandled exception of type 'System.NullReferenceException' occurred in ************.exe

Additional information: Object reference not set to an instance of an object.

I have no idea why this is occurring as I have ensured the DataTable always contains data I have even tried deleting the currently stored data to force it to use that defined within the else code block I have no idea how to fix it I have tried using a static DataTable in another file but all to no avail. Any help would be greatly appreciated.

Edit 2:

The code can be distilled down to this: public partial class frmMain : Form { public frmMain() { DataTable peers = new DataTable();

        peers.Columns.Add("nick");
        peers.Columns.Add("address");
        peers.Rows.Add("xnbya", "4lxi4nv5kkhyks2x.onion");
        peers.Rows.Add("curly", "h3m36rpq35rv7n36.onion");
        peers.PrimaryKey = new DataColumn[] { peers.Columns["address"] };

        lstRecentChats.DataSource = peers;
        lstRecentChats.DisplayMember = "nick";
    }
}

The error still occurs within just this code.

هل كانت مفيدة؟

المحلول

It seems lstRecentChats is null. If you put this code into your constructor before InitializeComponent method then you are trying to access lstRecentChats before it's initialized.So first call the InitializeComponent then set the DataSource.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top