mynamea sas mynamea sas - 4 months ago 50
C# Question

Get the last index/value from a listbox

I'm trying to get the last value within my listbox, so the user is able to enter number into the listbox. And I want to be able to output to a label text, what that value is. So it would show the last index from the listbox. Although, its just outputting the index number, -1.

if (lstHoldValue.SelectedIndices.Count > 0)
label1.Text = Convert.ToString(this.lstHoldValue.SelectedIndex = this.lstHoldValue.Items.Count - 1);

Jim Jim

To get the last item you use lstHoldValue.Items[lstHoldValue.Items.Count - 1] and together with a check (to see if the listbox has at least one item, before we execute code in the if statement) it will look like this:

if (lstHoldValue.Items.Count > 0)       
    label1.Text = lstHoldValue.Items[lstHoldValue.Items.Count - 1].ToString();