Sunday, February 13, 2011

Why do I get 3 values inserted into my C# combo box instead of just 1?

When reading the registry for file names I get 3 entries loading into my combo box for every 1 registry entry. If I have 1 file listed in the registry I would see :

Combo box values:

c:\file1.txt

<-----Blank here

c:\file1.txt

I have found the problem lies in this code, it hits 'if (previousFiles != null)' 3 times. How should I correct this?

for (int i = 0; i <= 5; i++)
     {
      Object previousFiles = OurKey.GetValue("Files" + i);
        if (previousFiles != null)
         {
                    comboBox1.Items.Add(previousFiles.ToString());
          }
     }

Many thanks Monday morning blues!

  • just add a "break;" after the first comboBox1.Items.Add(). it will leave the loop after the insert (if this is what you want).

    Claudio : That's not correct. He wants to know why he gets duplicates and blank items. Your solution would populate the combobox with one single item instead.
  • Is it a null on an empty string?

    From moogs
  • Looks like the issue is in your GetValue() function. Plus you should check for null and for empty string before adding to the combobox.

    From OJ
  • Assuming this is a string value what you may be seeing is a blank string coming back; it's hard to tell from the code.

    So instead of a null check cast the object first;

    Object previousFiles = OurKey.GetValue("Files" + i) as string;

    Then use

    string.IsNullOrEmpty()

    instead of a plain null check.

    From blowdart
  • Well, it should hit the if() statement 6 times, the comboBox1.Items.Add() statement 3 times. The logical explanation is that the real problem is located in the code that writes the registry keys. Run Regedit.exe to find out what is really stored in these registry key values.

  • Hi everyone, sorry it was in the code that wrote it, I was looking at an old reg key....sorry!

    OJ : So I was right then :)

0 comments:

Post a Comment