Reputation: 1
In my form have TextBox1 and ListBox1, buttonAdd, buttonRemove
buttonAdd => OK, I can do it. buttonRemove: When you delete a section: - Delete entry from textbox: Check one item in the listbox item should be deleted, if there are clear, if not, the message is not found - Delete the selected item in listbox
This is my idea:
private void butonRemove_Click(object sender, EventArgs e)
{
if (textbox1.Text != "")
{
int i = 0;
while (i <= listbox1.Items.Count)
{
string Item_remove = textbox1.Text;
if (listbox1.Items[i].ToString().Contains(Item_remove))
{
DialogResult conf_remove;
conf_remove = MessageBox.Show("Do you wwant to remove: " + listbox1.Items[i].ToString(), "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
if (conf_remove == DialogResult.Yes)
{
listbox1.Items.RemoveAt(i);
break;
}
else if (conf_remove == DialogResult.No)
i++;
}
else
{
MessageBox.Show("Not found");
break;
}
}
textbox1.Text = "";
textbox1.Focus();
}
else if (listbox1.SelectedIndex < 0)
MessageBox.Show("Please select item to remove");
else
listbox1.Items.Remove(listbox1.SelectedItem);
}
Please help me fix it, thank
Upvotes: 0
Views: 4575
Reputation: 995
This is what you are looking for, this controls all of the validation you need too.
if (ListBox.SelectedIndex == -1)
{
if (ListBox.NumberOfItems == 0) // if no index, need to select a row!
{
MessageBox.Show("No items to remove!");
}
else
{
MessageBox.Show("Please select an item first!");
}
}
else
{
ListBox.Items.RemoveAt(lstStorage.SelectedIndex);
}
This will remove the item that has been selected, with the validation that you require.
I have also commented some code to show you what parts mean. If you need any more explanations on how this works then just ask :)
Upvotes: 0
Reputation: 5150
Something like this?
void buttonRemove_Click(object sender, EventArgs e)
{
string matchcode = TextBox1.Text;
ListItem item = this.ListBox1.Items.FindByText(matchcode);
if (item != null)
{
//found
this.ListBox1.Items.Remove(item);
}
else
{
//not found
MessageBox.Show("is not found");
}
}
Upvotes: 0
Reputation: 485
Here's the code for remove item.
private void buttonRemove_Click(object sender, EventArgs e) {
if (listBox1.SelectedIndex == -1) { // Not Selected Anything
MessageBox.Show("Select an item to delete");
}
else {
listBox1.Items.RemoveAt(listBox1.SelectedIndex); // Remove item
}
}
Upvotes: 4