I have a ComboBox that have a list of manufacturers. When a user selects a manufacturer, a grid below is populated with data for the chosen manufacturer. That data can be mo
Night Coder's solution is elegant and concise. I have packaged it in a dll.
(I call it CustomControls.) To do this create a new class library and add the first few statements to Night Coder's solution (copied here as a convenience).
Once you have compiled the code, you can add it as a reference. I actually loaded the dll into my Visual Studio Tools pane. That way I can drag the control onto my form at design time. Conveniently, the new event shows up in the properties list.
use System.ComponentModel;
use System.Windows.Forms; //this will need to be added as a reference
//your namespace will name your dll call it what you will
namespace CustomControls
Night Coder's solution follows:
public class ComboBoxEx : ComboBox
{
public event CancelEventHandler SelectedIndexChanging;
[Browsable(false)]
public int LastAcceptedSelectedIndex { get; private set; }
public ComboBoxEx()
{
LastAcceptedSelectedIndex = -1;
}
protected void OnSelectedIndexChanging(CancelEventArgs e)
{
var selectedIndexChanging = SelectedIndexChanging;
if (selectedIndexChanging != null)
selectedIndexChanging(this, e);
}
protected override void OnSelectedIndexChanged(EventArgs e)
{
if (LastAcceptedSelectedIndex != SelectedIndex)
{
var cancelEventArgs = new CancelEventArgs();
OnSelectedIndexChanging(cancelEventArgs);
if (!cancelEventArgs.Cancel)
{
LastAcceptedSelectedIndex = SelectedIndex;
base.OnSelectedIndexChanged(e);
}
else
SelectedIndex = LastAcceptedSelectedIndex;
}
}
}