0

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

  • Well not really, I check on that question previously and tried many things in there but nothing seemed to work, still get the same issue. – Staling Marin Jan 13 '22 at 06:22
  • 1
    Probably `currentItem` is NULL. Did you try to debug and check? – Marco Jan 13 '22 at 06:38
  • 2
    If anything that you're using a member accessor syntax on (e.g. `.currentItem` or `.duration`) _is_ `null` then you will get this exception. – ProgrammingLlama Jan 13 '22 at 06:39
  • Well yes, it's exactly currentItem which is giving the error as I was supposing. The thing is I don't know how could I initialize that one, I tried many things and none of them worked, I would appreciate if you could give me an indication on how to do so. – Staling Marin Jan 13 '22 at 06:40
  • Forget about that, thank you very much for all of your answers, apparently all I needed to do was adding a ```?``` to the currentItem which I did previously but in a wrong position, it's all working now! – Staling Marin Jan 13 '22 at 06:43

1 Answers1

2

Do you have created the media player?

axWindowsMediaPlayer1 = new AxWMPLib.AxWindowsMediaPlayer();
axWindowsMediaPlayer1.CreateControl();
  • 1
    Thank you very much for your answer. The player itself was apparently created automatically when put into the form given that any other function besides the one that give the error work. I tried doing it anyway yet I got the exact same output. – Staling Marin Jan 13 '22 at 06:32