I have a listbox where i can delete items with a button but i want to also be able to delete with the delete key on my keyboard, I could not find a way on google so can someone please help me
Edit Its a winform application
This is the code for the delete button:
private void Button3Click(object sender, EventArgs e)
{
var application = this.GetCurrentApplication();
if (application == null)
{
MessageBox.Show("No Application selected");
return;
}
if (MessageBox.Show("You are about to delete application: " + Environment.NewLine + _applicationListBox.SelectedItem + Environment.NewLine + "Are you sure you want to delete the application?", "", MessageBoxButtons.YesNo) == DialogResult.No)
{
MessageBox.Show("The application will not be deleted.", "", MessageBoxButtons.OK);
}
else if (this._applicationListBox.SelectedIndex >= 0)
{
int index = _applicationListBox.SelectedIndex;
_toepassingIniFile.ToePassingen.Remove(application);
if (index == _toepassingIniFile.ToePassingen.Count)
--index;
application = index < 0 ? null : _toepassingIniFile.ToePassingen[index];
_toepassingIniFile.Save(application);
_applicationListBox.DataSource = null;
_applicationListBox.DataSource = _toepassingIniFile.ToePassingen;
_applicationListBox.SelectedIndex = index;
}
}
Answer thank to Jonesy
private void ApplicationListBoxPreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
{
if (e.KeyCode ==Keys.Delete )
{
deletefromlistbox();
}
if (e.KeyCode == Keys.Insert)
{
Refreshapplication();
}
}
Refreshapplication
private void Refreshapplication()
{
var newapplication = new NewApplication(_toepassingIniFile);
if (newapplication.Run())
{
_applicationListBox.DataSource = null;
_applicationListBox.DataSource = _toepassingIniFile.ToePassingen;
_applicationListBox.SelectedIndex = _toepassingIniFile.ToePassingen.Count - 1;
_controllercombobox.DataSource = null;
_controllercombobox.DataSource = _controllerIniFile.Controllers;
}
}
applicationListBox.PreviewKeyDown +=new PreviewKeyDownEventHandler(applicationListBox_PreviewKeyDown);
then
void applicationListBox_KeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Delete)
{
//delete
}
}
then do like msm8bball said and abstract out that code so both button click and previewkeydown call the delete method
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With