locked
Null Reference Exception RRS feed

  • Question

  • Hello. I'm trying to catch a null reference exception and having a hard time with it. It occurs when I first select the trackLenght text box before selecting list view. If done in reverse, no problem. Any help would be greatly appreciated

    This is for the Hashtable. Note where it says " String text = hsTrackLength[i].ToString();" this is where it's giving me the error.

            private Hashtable hsTrackLength = new Hashtable();
            private string id;
            private int albumID;
            private string AlbumID;
            private void AddIntoHashTable()
            {
                int index = -1;
                for (int i = 0; i < lstViewTracks.Items.Count; i++)
                {
                    if (lstViewTracks.Items[i].Selected)
                    {
                        index = i;
                        break;
    
                    }
                }
    
                if (hsTrackLength.ContainsKey(index))
                {
                    //no entry
                    hsTrackLength[index] = txtTrackLength.Text;
                }
                else
                    hsTrackLength.Add(index, txtTrackLength.Text);
            }
    
            private string GetTrackLengthFromHashTable(int index)
            {
    
                for (int i = 0; i < hsTrackLength.Count; i++)
                {
                    if (i == index)
                    {
                        return string.Format("{0}", hsTrackLength[i]);
    
                    }
    
                }
                return string.Empty;
            }
            private string GetTotalTracksLength()
            {
    
                
                System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex("[0-9][0-9][0-9][0-9]");
                int sec = 0;
                
                
                for (int i = 0; i < hsTrackLength.Count; i++)
                {
                    String text = hsTrackLength[i].ToString();
                    if (reg.IsMatch(text))
                    {
                        sec += Convert.ToInt32(text.Substring(0, 2)) * 60;
                        sec += Convert.ToInt32(text.Substring(2, 2));
                    }
    
    
                }
                return String.Format("{0}:{1:D2}", sec / 60, sec % 60);
            }
                
    

    Here's the list view selected index method in case it helps

    private void lstViewTracks_SelectedIndexChanged(object sender, EventArgs e)
                
            {
                for (int i = 0; i < lstViewTracks.Items.Count; i++)
                {
                    if (lstViewTracks.Items[i].Selected)
                    {
                        txtSongEdit.Text = lstViewTracks.Items[i].SubItems[1].Text;
                        String text = GetTrackLengthFromHashTable(i);
                        try
                        {
                            int hours = Convert.ToInt32(text.Substring(0, 2));
                            int mins = Convert.ToInt32(text.Substring(2, 2));
                            txtTrackLength.Text = String.Format("{0}:{1:D2}", hours, mins);
                        }
                        catch (Exception ex)
                        {
                            txtTrackLength.Text = text;
                        }
    
                        txtTotalTime.Text = String.Format("{0}", GetTotalTracksLength());
                        lbtAlbumTime.Text = String.Format("{0}", GetTotalTracksLength());
                    }
                }
            }
    


     

     


    PCRider
    Wednesday, September 21, 2011 3:07 PM

Answers

  • Disable (Enabled = false) the text box until a song is selected.
    • Marked as answer by PCRider Wednesday, September 21, 2011 5:21 PM
    Wednesday, September 21, 2011 4:55 PM

All replies

  • You should get a NullReferenceException only in two cases: either hsTrackLength is null or hsTrackLength[i] is null. You set hsTrackLength in the first line of your sample and nowhere else, it shouldn't be null. As far as I know, a textbox never returns a null Text, so the hashtable shouldn't contain any null.

    Put a breakpoint on the line, execute your program, and when it breaks on the breakpoint, check if hsTrackLength is null or if it contains a null.

    Wednesday, September 21, 2011 3:26 PM
  • It only happens if I select the text box first. If I select the list view control first, no problem. Which is how it's supposed to work but if someone puts in time in text box before selecting a song that's when i comes up
    PCRider
    Wednesday, September 21, 2011 3:47 PM
  • This takes out the null reference but doesn't give me the message

    for (int i = 0; i < hsTrackLength.Count; i++)
                {
    
                    String text = hsTrackLength.ToString();
                    if (reg.IsMatch(text))
                    {
                        sec += Convert.ToInt32(text.Substring(0, 2)) * 60;
                        sec += Convert.ToInt32(text.Substring(2, 2));
                    }
    
                    if (hsTrackLength.Count == 0)
                        MessageBox.Show("Please select a song first");
                }
    



    PCRider
    Wednesday, September 21, 2011 4:22 PM
  • Read this http://msdn.microsoft.com/en-us/library/system.collections.hashtable.item.aspx, especially "If the specified key is not found, attempting to get it returns null". So there is no key "i" in the hashtable yet, a null is returned instead and calling ToString() on null triggers the exception. You should handle this gracefully, for example:

    object len = hsTrackLength[i];
    if (len == null)
      continue;
    
    String text = len.ToString();
    
    

     


    • Edited by MCCZ Wednesday, September 21, 2011 4:30 PM
    • Marked as answer by PCRider Wednesday, September 21, 2011 4:44 PM
    • Unmarked as answer by PCRider Wednesday, September 21, 2011 4:45 PM
    Wednesday, September 21, 2011 4:29 PM
  • Great! Now is there a way to get the message to come UP?
    PCRider
    Wednesday, September 21, 2011 4:35 PM
  • Basically, it's not a best practice to force users to fill the data in a particular order. You should rather overcome this difficulty and wait until all required fields are filled before you start doing anything.
    Wednesday, September 21, 2011 4:40 PM
  • Well, in this case you have to because the song time is linked up to the selected index. So if you say select "Love Me Do" by the Beatles, you need to add the correct time say 2:50 to that song. You cant say add time then select song. Doesn't work that way.. So in this case the user needs to know that they have to select a song title first.
    PCRider
    Wednesday, September 21, 2011 4:53 PM
  • Disable (Enabled = false) the text box until a song is selected.
    • Marked as answer by PCRider Wednesday, September 21, 2011 5:21 PM
    Wednesday, September 21, 2011 4:55 PM