Reputation: 157
I have a button that adds items to a check list box.
private void btnDelivery_Click(object sender, EventArgs e)
{
deliveryForm.deliverytrips = new DeliveryTrips();
deliveryForm.ShowDialog();
if (deliveryForm.deliverytrips != null)
{
DeliveryTrips newApp = deliveryForm.deliverytrips;
theDelivery.addDeliveryTrip(newApp);
}
updateList();
}
private void updateList()
{
clbSummary.Items.Clear();
List<String> listOfDelivery = theDelivery.listDeliveryTrips();
clbSummary.Items.AddRange(listOfDelivery.ToArray());
}
Using buttons how could I edit, What I have added to the checklist box or delete it from the check list box?
just now i have this for editing a item
int index = clbSummary.SelectedIndex;
DeliveryTrips selected = theDelivery.getDeliveryTrips(index);
deliveryForm.deliverytrips = selected;
deliveryForm.ShowDialog();
updateList();
but that only edits the items if selected and not checked, same with the remove button, it only removes the item if selected and not checked .
Thanks
Upvotes: 0
Views: 2214
Reputation: 7773
Delete is the easy part. If your list supports a single item selected (SelectionMode
One
), you can do something like
private void DeleteButton_Click(object sender, EventArgs
{
clbSummary.Items.RemoveAt(clbSummary.SelectedIndex);
}
Now, if you support multiple selection (SelectionMode
MultiSimple
/MultiExtended
- Works for standard lists, not CheckboxLists), the following code will remove the entire selection
private void DeleteButton_Click(object sender, EventArgs e)
{
for(int i = clbSummary.SelectedIndices.Count - 1; i >= 0; --i)
{
clbSummary.Items.RemoveAt(clbSummary.SelectedIndices[i]);
}
}
Here, it is very important to reverse the order, otherwise the removal in items will shift the content of your clbSummary
and the more you delete items, the bigger the offset will be.
If you want to remove the Checked items, it's the same thing, but you use CheckedIndices
private void DeleteButton_Click(object sender, EventArgs e)
{
for (int i = clbSummary.CheckedIndices.Count - 1; i >= 0; --i)
{
clbSummary.Items.RemoveAt(clbSummary.CheckedIndices[i]);
}
}
To edit, I would suggest creating a form to edit the content of your item, or if it's only a string, maybe a simple input dialog would be sufficient (I really simplified it using a reference to Microsoft.VisualBasic
to use an InputBox
). Usually your items might correspond to more complex objects than strings so a proper Editor
might be necessary (a Form made specifically to edit your items)
private void EditButton_Click(object sender, EventArgs e)
{
string content = clbSummary.SelectedItem.ToString();
string newValue = Interaction.InputBox("Provide new value", "New Value", content, -1, -1);
int selectedIndex = clbSummary.SelectedIndex;
clbSummary.Items.RemoveAt(selectedIndex);
clbSummary.Items.Insert(selectedIndex, newValue);
}
Upvotes: 2