mynamea sas mynamea sas - 1 year ago 133
C# Question

Get the last index/value from a listbox C#

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
Answer Source

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();
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download