Reputation: 282825
I've got a ListBox with a bunch of items in it. The user can click an item to edit its contents. How do I prevent the user from deselecting all items? i.e., the user shouldn't be able to have nothing selected.
Upvotes: 9
Views: 4478
Reputation: 3079
If your ListView
supports Multiple
selection, this worked for me.
var found = e.RemovedItems.Cast<User>()
.Where(user => user.Id == Id);
if (found.Any())
{
User user = found.First();
user.Selected = true;
(e.Source as ListView).SelectedItems.Add(user);
}
This solution should work regardless of Single
or Multiple
SelectionMode
. If you have multiple items that you want them to be kept selected, adjust the code accordingly by adding your object back into SelectedItems
property.
Upvotes: 0
Reputation: 1574
This Works for Sure to Prevent User from Deselect... Add those 2 Events to your checkedListBox1 and set the Property CheckOnClick to "True" in Design Mode. (MSVS2015)
private void checkedListBox1_SelectedValueChanged(object sender, EventArgs e)
{
checkedListBox1.SetItemChecked(checkedListBox1.SelectedIndex, true);
}
private void checkedListBox1_MouseDoubleClick(object sender, MouseEventArgs e)
{
checkedListBox1.SetItemChecked(checkedListBox1.SelectedIndex, true);
}
Upvotes: 1
Reputation: 282825
One solution, as suggested by amccormack
:
private void hostsListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if(lstHosts.SelectedItem == null)
{
if(e.RemovedItems.Count > 0)
{
lstHosts.SelectedItem = e.RemovedItems[0];
}
Upvotes: 0
Reputation: 6456
There is a case missing in your situation, which is when the list is cleared you will reselect an item there is no longer on the list. I solve this by adding an extra check.
var listbox = ((ListBox)sender);
if (listbox.SelectedItem == null)
{
if (e.RemovedItems.Count > 0)
{
object itemToReselect = e.RemovedItems[0];
if (listbox.Items.Contains(itemToReselect))
{
listbox.SelectedItem = itemToReselect;
}
}
}
I then put this inside a behaviour.
Upvotes: 6
Reputation: 971
To disable on or more options in your listbox/dropdown, you can add the "disabled" attribute as shown below. This prevent the user from selection this option, and it gets a gray overlay.
ListItem item = new ListItem(yourvalue, yourkey);
item.Attributes.Add("disabled","disabled");
lb1.Items.Add(item);
Upvotes: 0
Reputation: 13927
I'm not sure if there is a direct way to disable deselecting an Item, but one way which would be transparent to the user is to keep track of the last selected Item, and whenever the SelectionChanged event is raised and the selected index is -1, then reselect the last value.
Upvotes: 2