Hey guys, I am needing to detect when the last item in a listbox is selected. I first tried comparing the listbox.items.count with the listbox.selectedIndex, but unfortunately, whenever i load the items from a file to the listbox, there are 1 or two extra items at the end that are blank.

I then tried going to the last index in the listbox, and if it was "", then i went up an item, until i got one that wasn't "", and that would be my last item. Unfortunately, that didn't seem to work.

Is there an easy way to detect the last NON NULL item in a listbox??

Dani AI

Generated

Short answer: stop adding blank entries and then SelectedIndex == Items.Count - 1 will work reliably. The two issues in the thread are (1) consuming the input twice inside the loop (which can return null at EOF) and (2) accidentally adding the wrong object instead of the line string. you were calling ReadLine more than once per iteration; the idea to skip empty lines is correct but the sample added the wrong value.

Use a single ReadLine per loop, trim the line, skip empty/whitespace, and always check the OpenFileDialog result. Example (safe, minimal):

if (openFileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
    listBoxAccounts.Items.Clear();
    using (var sr = new System.IO.StreamReader(openFileDialog.FileName))
    {
        string line;
        while ((line = sr.ReadLine()) != null)
        {
            line = line.Trim();
            if (line.Length == 0) continue;
            listBoxAccounts.Items.Add(line);
        }
    }
}

Alternatives: System.IO.File.ReadLines(path) is convenient for small files; trim and skip String.IsNullOrWhiteSpace (or Trim().Length==0 if using an older runtime).

If you need to find the last non-empty item after population, walk backwards rather than trusting a possibly-poisoned Count:

int last = -1;
for (int i = listBoxAccounts.Items.Count - 1; i >= 0; i--)
{
    var s = listBoxAccounts.Items[i] as string;
    if (!string.IsNullOrEmpty(s) && s.Trim().Length > 0) { last = i; break; }
}
if (last >= 0) listBoxAccounts.SelectedIndex = last;

Final tips: always check SelectedIndex >= 0 before calling SelectedItem.ToString(), and use using so files are closed. If blank lines persist, open the text file in a plain editor to confirm there are no hidden whitespace or BOM characters.

Recommended Answers

All 8 Replies

Please show us your code.

if (Listbox1.SelectedIndex == Listbox1.Items.Count - 1)
            {

            }

Please show us your code.

if (Listbox1.SelectedIndex == Listbox1.Items.Count - 1)
            {

            }

yes sir, as I said in my post, I have already tried comparing the listbox count and listbox index, and it doesn't work b/c for some reason I am getting extra NULL valued items at the end of the listbox.

Can you post that code which populates listbox please? For easy readability, always wrap programming code within posts in CODE

the code used to populate the listbox was this:

this.listBoxAccounts.Items.Clear();
            OpenFileDialog Open = new OpenFileDialog();
            Open.Filter = "Text Document|*.txt|All Files|*.*";
            try
            {
                Open.ShowDialog();
                StreamReader Import = new StreamReader(Convert.ToString(Open.FileName));
                while (Import.Peek() >= 0)
                    listBoxAccounts.Items.Add(Convert.ToString(Import.ReadLine()));
            }
            catch (Exception ex)
            {
                MessageBox.Show(Convert.ToString(ex.Message));
                return;
            }

Do not allow to add empty or null string into items collection.

string[] lines = System.IO.File.ReadAllLines(Open.FileName);

listBoxAccounts.Items.Clear();

foreach (string line in lines)
{
  if (!string.IsNullOrEmpty(line))
   {
    listBoxAccounts.Items.Add(listBoxAccounts);
   }
}

ok..so i did what u said, so now this is my code

this.listBoxAccounts.Items.Clear();
            OpenFileDialog Open = new OpenFileDialog();
            Open.Filter = "Text Document|*.txt|All Files|*.*";
            try
            {
                Open.ShowDialog();
                StreamReader Import = new StreamReader(Convert.ToString(Open.FileName));
                while (Import.Peek() >= 0)
                    if (!string.IsNullOrEmpty(Import.ReadLine()))
                    {
                        listBoxAccounts.Items.Add(Convert.ToString(Import.ReadLine()));
                    }
            }
            catch (Exception ex)
            {
                MessageBox.Show(Convert.ToString(ex.Message));
                return;
            }


            listBoxAccounts.SelectedIndex = (listBoxAccounts.Items.Count - 1);
            accSwitcher = listBoxAccounts.SelectedItem.ToString();
            

            MessageBox.Show(accSwitcher);

but it still adds a null line as the last item in teh listbox.

Please upload that datafile here. (Use attachment option).

umm i would rather not upload the file b/c it is a list of accounts and passwords lol...but basically it looks like this

acc1:pass1
acc2:pass2
acc3:pass3
etc

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.