Reputation: 9963
I have a function that deselect all selected items in the listbox when the user right clicks on listbox. Is there a way to apply this function to all listboxes in my project?
I want to know if there's another way , not making a class and put the function in the class etc:
public class selectedListbox{
private void setSelected(ListBox details){
details.MouseDown += new System.Windows.Forms.MouseEventHandler(this.listBoxDeselectAll);
}
private void listBoxDeselectAll(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Right)
{
((ListBox)sender).ClearSelected();
}
}
}
and then for each listbox to do this:
selectedListBox h = new selectedListBox();
h.setSelected(listboxNameHere);
Upvotes: 1
Views: 1356
Reputation: 3247
maybe with an extension + lambda?
public static class ListBoxSelectExtension
{
public static void SetSelected(this ListBox Me)
{
Me.MouseDown +=
(sender, e) =>
{
if (e.Button == MouseButtons.Right)
((ListBox)sender).ClearSelected();
};
}
}
this way you can do the following without having to instantiate a new class or having to have all your listboxes be a derived class:
MyListBox1.SetSelected();
MyListBox2.SetSelected();
etc.
Upvotes: 2
Reputation: 47490
public class MyListBox : ListBox
{
public sListBox() : base()
{
MouseDown += new System.Windows.Forms.MouseEventHandler( this.MouseDownFired );
}
private void MouseDownFired(object sender, MouseEventArgs args)
{
if ( args.Button == MouseButtons.Right )
{
SelectedItems.Clear();
}
}
Upvotes: 1
Reputation: 1383
The most straightforward method would be to create a class that inherits from ListBox:
public class CustomListBox : ListBox
{
public void SetSelected()
{
this.MouseDown += new MouseEventHandler(this.DeselectAll);
}
public void UnsetSelected()
{
this.MouseDown -= new MouseEventHandler(this.DeselectAll);
}
private void DeselectAll(object sender, MouseEventArgs e)
{
// ...
}
}
You would use your custom list box in the same way that you would use a standard list box.
Upvotes: 1