Null reference on an initiated variable [duplicate]
I'm using wmp from C# forms to display the length of a media file on my form, however, when I try to do so the result is an exception saying
System.NullReferenceException: 'Object reference not set to an instance of an object.'
My code is the following.
private void timer1_Tick(object sender, EventArgs e)
{
if(axWindowsMediaPlayer1.playState == WMPLib.WMPPlayState.wmppsPlaying)
{
progressBar1.Maximum = (int)axWindowsMediaPlayer1.Ctlcontrols.currentItem.duration;
progressBar1.Value = (int)axWindowsMediaPlayer1.Ctlcontrols.currentPosition;
}
try
{
label2.Text = axWindowsMediaPlayer1.Ctlcontrols.currentPositionString;
label3.Text = axWindowsMediaPlayer1.Ctlcontrols.currentItem.durationString.ToString();
}
catch
{
}
}
I've checked my labels and both of them are initiated, the error is happening with label3, apparently the exception is caused because axWindowMediaPlayer1. Ctlcontrols.currentItem.durationString
is not initialized but I don't know how to initialize it. label2 has no issues whatsoever though it uses a similar function.
how could I possibly fix this. Many thanks
Solution 1:
Do you have created the media player?
axWindowsMediaPlayer1 = new AxWMPLib.AxWindowsMediaPlayer();
axWindowsMediaPlayer1.CreateControl();