Deleting last Listbox item

G

Guest

Hi,

I have a windows form with a listbox control. My code all works correctly
when deleting an item from the listbox except the last item. I get the
following message when trying to delete the last item:-

Specified argument was out of the range of valid values. Parameter name:
'64' is not a valid value for 'Value'.

The 64 reduces depending on how many listbox items are displayed.

Also (related) when deleting the last and only item from the listbox, the
error message changes to:

Specified argument was out of the range of valid values. Parameter name: '0'
is not a valid value for 'Value'.

My code is

private void _DoDelUser()
{

// Prompt the user first.
if (MessageBox.Show(this, "This will delete the selected user - continue?",
this.Text, MessageBoxButtons.OKCancel, MessageBoxIcon.Question) !=
DialogResult.OK)
return;

// Get the current user index.
int userIndex = m_listBoxUsers.SelectedIndex;

// Should we ignore the the event?
if (userIndex == -1)
return;

// Get the identifier.
int userID = (Int32)m_userTable.Rows[userIndex]["user_id"];

// Delete the user.
UserManager.Delete(userID);

// Get the GUI state.
int index = m_listBoxUsers.SelectedIndex;

// Update the tables
m_userTable = UserManager.FindAll().Tables[0];

// Bind the GUI to the tables.
m_listBoxUsers.DataSource = m_userTable;
m_listBoxUsers.DisplayMember = "user_name";
m_listBoxUsers.SelectedIndex = index;

} // End _DoDelUser()

Thanks in advance and King Regards
 
I

Ignacio Machin \( .NET/ C# MVP \)

Hi,

It may give you error, especially if you delete the last one ( as you are
experimenting )
The thing is that you are saving the selectedIndex BEFORE delete it, then
later you are reassign it to the listbox , BUT the listbox's item count will
be less that before delete the element

Beside, what is the point in keep the selected index if that is the one you
are going to delete after all?

If what you want is to select the next one, well then you have to decide
what to do when the selected is the last one, either select none:
listBoxUsers.SelectedIndex = -1;

or just select the current last one
listBoxUsers.SelectedIndex = listBoxUsers.Items.Count-1;


cheers,
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top