So I am drawing a blank on how to make the program read the list and see that the item has not already been added. Here is my code, this was my first idea but I am not sure what to write so that the user cannot add the select item twice.
For example in lstAvailable there is an option named Floormats, the user can add Floormats to lstSelected but if they try to after that I need the message box to say item already selected
// CREATE LIST FOR AVAILABLE OPTION PRICES (parallel to listbox)
List<double> dblAvailableItems = new List<double> { 775.18, 567.99, 312.03, 1934.99, 609.82, 1251.04, 190.08, 82.00, 600.00 };
// CREATE LIST FOR SELECTED OPTION PRICES (parallel to listbox - empty to start)
List<double> dblOrder = new List<double>();
public frmPriceCar()
{
InitializeComponent();
}
private void lstAvailableOptions_DoubleClick(object sender, EventArgs e)
{
// DETERMINE IF OPTION HAS NOT ALREADY BEEN SELECTED
if (lstAvailableOptions.SelectedIndex.ToString() == lstSelectedOptions.Items.ToString())
{
MessageBox.Show("Item already added");
return;
}
if (lstAvailableOptions.SelectedIndex > -1)
{
//ADD OPTION TO SELECTED OPTIONS LISTBOX
dblOrder.Add(dblAvailableItems[lstAvailableOptions.SelectedIndex]);
//ADD OPTION PRICE TO SELECTED OPTIONS LIST
lstSelectedOptions.Items.Add(lstAvailableOptions.Items[lstAvailableOptions.SelectedIndex]);
//CALL CALCULATE METHOD TO CALCULATE TOTALS AND DISPLY TO SCREEN
CalcTotal();
}
}
```
CodePudding user response:
Instead of checking in the UI (lstAvailableOptions
), just check in the list itself (dblOrder
):
if (dblOrder.Contains(lstAvailableOptions.SelectedItem))
{
MessageBox.Show("Item already added");
return;
}
Also from a UX standpoint, why do you need to bother the user with a pop-up if he adds something twice? Just silently do the right thing in your code (make sure that it's only added once):
if (dblOrder.Contains(lstAvailableOptions.SelectedItem)) return;
And you can even go further than that. If instead of:
List<double> dblOrder = new List<double>();
you use:
HashSet<double> dblOrder = new HashSet<double>();
you can completely skip checking if it's already in the list. A HashSet
will not add it twice.... it automatically makes sure that there's only one of each item.
CodePudding user response:
This line
lstAvailableOptions.SelectedIndex.ToString() == lstSelectedOptions.Items.ToString()
compares an index to a collection, that doesn't make sense. If you step through it with a debugger you'll probably see that you are comparing e.g.
"1" == "System.Collections.Generic.List`1[System.Double]"
and that comparison of course always returns false.
Check instead if lstSelectedOptions contains the selected item, or directly if dblOrder contains the selected item:
if (dblOrder.Contains(dblAvailableItems[lstAvailableOptions.SelectedIndex])
{
MessageBox.Show("Item already added");
return;
}