Reputation: 2988
I get this weird NullReferenceExcpetion, in a WPF application. I don't get this every time, even if I do same operation. Can anyone please explain the reason for this,
public class AmazonUrl
{
public string Url { get; set; }
}
public partial class MainWindow : Window
{
public ObservableCollection<AmazonUrl> AmazonUrlList { get; set; }
public MainWindow()
{
InitializeComponent();
DataContext = this;
AmazonUrlList = new ObservableCollection<AmazonUrl>();
}
public List<string> getURLList()
{
List<string> urlList = new List<string>();
for(int i = 0; i < AmazonUrlList.Count; i++)
{
AmazonUrl url = AmazonUrlList[i];
if (url == null)
continue;
String str = url.Url.ToString().Trim();
if (str.Length > 0)
urlList.Add(str);
}
return urlList;
}
private void openMenuItem_Click(object sender, RoutedEventArgs e)
{
List<string> urlList = getURLList();//This is where exception occur
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.Filter = "SCR File (.scr)|*.scr|All Files|*.*";
if (openFileDialog.ShowDialog() != true){ ... }
}
Note: After adding these lines I made lots of changes to the application, and recompiled several times. So this is not a problem with Build or Compiling
Edit: My stack trace can find from here, https://pastebin.com/2vyH1qah
Upvotes: 0
Views: 117
Reputation: 106
I can't reproduce the error, it must be something with your collection. What does your collection look like? This should fix the problem either way--
public partial class MainWindow : Window
{
private static object lockObj = new object(); //Add
...
public List<string> getURLList()
{
List<string> urlList = new List<string>();
for (int i = 0; i < AmazonUrlList.Count; i++)
{
Amazon url = new AmazonUrl(); // Add
url = AmazonUrlList[i]; // Update
...
private void openMenuItem_Click(object sender, RoutedEventArgs e)
{
lock (lockObj) // Add
{
List<string> urlList = getURLList(); //This is where exception occur
}
Upvotes: 1