C# Saving in loop error
I get an error "Object reference not set to an instance of an object." when trying to save all items from a listbox with this method.
writer = new StreamWriter(saveBox.File开发者_Go百科Name);
foreach (var item in LstResults.Items.Cast<object>().Where(item => string.IsNullOrEmpty(item.ToString())))
{
writer.Write(item.ToString().Trim() + ",");
}
writer.Close();
What am I doing wrong? The list is holding about 80k items.
Shouldn't this be
item => !string.IsNullOrEmpty(item.ToString())
for this loop to make sense? If you are pulling back items which have a null
ToString()
result, you're then calling Trim
on a null object.
The following are your suspects:
- saveBox
- item (one of the items in the ListBox)
- the result of item.ToString (very unlikely)
If any of the ListBox's items is null, you're getting an exception on that first ToString call.
精彩评论