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
Abstract out your logic for the deletion into it's own function. Have Button3Click call this function.
Then, add a new function that handles deletion, and have it also call the new function. Use this event: http://msdn.microsoft.com/en-us/library/system.windows.forms.control.onpreviewkeydown.aspx
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.