Hi, why it's always got the error message said that "NullReferenceException Unhandled" ?
Here is my code:
public partial class MainPage : PhoneApplicationPage
{
private FlashCard _flashCard;
// Constructor
public MainPage()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
// This could go under somewhere like a load new flash card button or
// menu option etc.
try
{
_flashCard = new FlashCard(@"D:\My Workspaces\Windows Phone 7 Solution\SimpleFlashCard\App.xaml");
}
catch (Exception)
{
// do something
}
}
private void btnLeft_Click(object sender, RoutedEventArgs e)
{
DisplayPrevious();
}
private void btnRight_Click(object sender, RoutedEventArgs e)
{
DisplayNext();
}
private void DisplayNext()
{
FlashText.Text = _flashCard.GetNextLine();
}
private void DisplayPrevious()
{
FlashText.Text = _flashCard.GetPreviousLine();
}
}
and a Class named "FlashCard":
public class FlashCard
{
private readonly string _file;
private readonly List<string> _lines;
private int _currentLine;
public FlashCard(string file)
{
_file = file;
_currentLine = -1;
// Ensure the list is initialized
_lines = new List<string>();
try
{
LoadCard();
}
catch (Exception ex)
{
// either handle or throw some meaningful message that the card
// could not be loaded.
}
}
private void LoadCard()
{
if (!File.Exists(_file))
{
// Throw a file not found exception
}
using (var reader = File.OpenText(_file))
{
string line;
while ((line = reader.ReadLine()) != null)
{
_lines.Add(line);
}
}
}
public string GetPreviousLine()
{
// Make sure we're not at the first line already
if (_currentLine > 0)
{
_currentLine--;
}
return _lines[_currentLine];
}
public string GetNextLine()
{
// Make sure we're not at the last line already
if (_currentLine < _lines.Count - 1)
{
_currentLine++;
}
return _lines[_currentLine];
}
}
The solution is about to made a simple Flash Card application. While I am executing the code, and hitting the 'Next' button, it always error under the "FlashText.Text = _flashCard.GetNextLine();" line said "NullReferenceException was unhandled", and so for the 'Previous' button under the line "FlashText.Text = _flashCard.GetPreviousLine();".
Please help. Thanks.