Prevent user from deselecting an item in a ListBox?
I've got a ListBox with a bunch of items in it. The user can click an item t开发者_JAVA百科o 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.
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.
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.
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);
}
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);
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];
}
精彩评论