Reputation: 183
I'm trying to fill a list view from a datatable but when I run the code I recieve a weird error that I can't figure out.
The code:
DataTable allTracks = tracks.getByMedia();
for (int i = 0; i < allTracks.Rows.Count; i++) {
DataRow r = allTracks.Rows[i];
ListViewItem lvi = new ListViewItem();
lvi.Text = r["track_number"].ToString();
lvi.SubItems.Add(r["track_name"].ToString());
lvTracks.Items.Add(lvi);
}
Error :
Object reference not set to an instance of an object.
The program thinks that the lvi variable is not set or null, but when I go into Debug mode, I can see that lvi is definitly initialized and set and is containing the
right text + sub item . :S
Also if I put this instead of the
lvTracks.Items.Add(lvi);
Messagebox.Show(lvi.Text)
It shows the correct value, and does not trigger the error....
Upvotes: 0
Views: 535
Reputation: 867
It seems the one of the fields contain a null value as converting null values to String Throws error.
I dont think Listviewitem is null in any case beacuase it gets intantiated every time in loop
try
DataTable allTracks = tracks.getByMedia();
foreach(DataRow r in allTracks.Rows) {
string track_number= r["track_number"]!=System.DBNull.Value?r["track_number"].ToString():"";
string track_name=r["track_name"]!=System.DBNull.Value?r["track_name"].ToString():"";
ListViewItem lvi = new ListViewItem();
lvi.Text = track_number;
lvi.SubItems.Add(track_name);
if(lvTracks!=null)
{
lvTracks.Items.Add(lvi);
}
}
Please note that there exists two different null One for .Net CLR this is 'null' and the other for Database that is 'Syatem.DBNull.Value'
Upvotes: 0
Reputation: 44921
There is nothing apparently wrong with the listviewitem; I suspect that the error is that one of your field names in the data row is incorrect.
Upvotes: 1