我有一些行,希望用户可以通过ctrl + a选择多个行,然后可以通过按键盘上的Delete键删除选定的项目。
我的代码不起作用。列表项可以通过ctrl + A进行选择,但是按Delete键后,仅一项将被删除。
private void lvTasks_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.A && e.Control)
{
lvTasks.MultiSelect = true;
foreach (ListViewItem item in lvTasks.Items)
{
item.Selected = true;
}
}
if (e.KeyCode == Keys.Delete)
foreach (ListViewItem eachItem in lvTasks.SelectedItems)
{
DeleteTask();
}
}
public void DeleteTask()
{
if (lvTasks.SelectedItems.Count > 0)
{
lvTasks.Items.Remove(lvTasks.SelectedItems[0]);
Statics.SaveTasks(lvTasks.Items.Cast<ListViewItem>().Select(l => (Task)l.Tag).ToArray());
UpdateTaskProgress(new Task());
txtDownloadLink.Text = "";
txtRarPassword.Text = "";
txtReferenceLink.Text = "";
chkBackupResource.Checked = Properties.Settings.Default.BackupSource;
chkClearExtracted.Checked = Properties.Settings.Default.CleanExtract;
chkRemoveRar.Checked = Properties.Settings.Default.RemoveRar;
chkUseIDM.Checked = Properties.Settings.Default.UseIDM;
chkRemoveDownload.Checked = Properties.Settings.Default.RemoveDownload;
gbTaskProgress.SuspendLayout();
settings = Statics.LoadSettings();
gbTaskProgress.Controls.Clear();
int max = Enum.GetValues(typeof(TaskProgresses)).Cast<int>().LastOrDefault();
for (int i = 0; i <= max; i++)
gbTaskProgress.Controls.Add(new TaskProgress(i + 1) { Left = 10, Top = (20 + 24 * i), Caption = ((TaskProgresses)i).ToString().CapitalSplit(), Task = new Task() });
gbTaskProgress.ResumeLayout();
lvTasks.Items.Clear();
Statics.LoadTasks().ToList().ForEach(t =>
{
ListViewItem lvi = new ListViewItem(new string[] { (lvTasks.Items.Count + 1).ToString(), t.TaskName, $"{t.TaskId}", $"{t.Progress}-{t.Status}" });
t.UI = this;
if (t.Status == TaskStatuses.Active) t.Status = TaskStatuses.NotStarted;
lvi.Tag = t;
lvi.SubItems[0].Tag = t.Progress;
lvTasks.Items.Add(lvi);
});
}
}
答案 0 :(得分:2)
private void lvTasks_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.A && e.Control)
{
lvTasks.MultiSelect = true;
foreach (ListViewItem item in lvTasks.Items)
{
item.Selected = true;
}
}
if (e.KeyCode == Keys.Delete)
for (int i = lvTasks.SelectedItems.Count - 1; i >= 0; i--)
{
ListViewItem itm = lvTasks.SelectedItems[i];
lvTasks.Items[itm.Index].Remove();
}
}
编辑
您的行lvTasks.Items.Remove(lvTasks.SelectedItems[0]);
是问题。您只删除索引为0的项目。您需要在它们上循环。
编辑2 仅在您要删除所有项目时才有效。如果您确实只想删除选定的项目。更改for循环并删除列表:
for (int i = lvTasks.SelectedItems.Count - 1; i >= 0; i--)
{
ListViewItem itm = lvTasks.SelectedItems[i];
lvTasks.Items[itm.Index].Remove();
}
应该可以。
答案 1 :(得分:0)
我会使用while循环:
if (e.KeyCode == Keys.Delete)
{
while (lvTasks.SelectedItems.Count > 0)
{
lvTasks.SelectedItems[0].Remove();
}
}
已更正。谢谢塞萨尔!