[英]Removing the selected Item from the list
Basically it's a contact list, select the contact from the listbox and hit the remove button, deleting it from the list. 基本上,这是一个联系人列表,从列表框中选择联系人,然后单击“删除”按钮,将其从列表中删除。
private void btnRmv_Click(object sender, EventArgs e)
{
try{
listBox.Items.Remove(listBox.SelectedItems[0]);
people.RemoveAt(listBox.SelectedIndex);
}
catch { }
}
This code seems to delete the Contacts from the listbox, but if I save my program and open it up again, the contact is back there. 这段代码似乎从列表框中删除了联系人,但是如果我保存程序并再次打开它,则联系人又回到了那里。 I am saving all the contacts in an Xml file.
我将所有联系人保存在Xml文件中。 The program auto saves on exit, and does have a manual save button.
该程序在退出时自动保存,并且具有手动保存按钮。
Thanks 谢谢
Try to remove from the "people" first and then remove it from the list box or else take the selected index to a parameter. 尝试先从“人员”中删除,然后从列表框中删除它,否则将所选索引作为参数。 sample code is pasted below
示例代码粘贴在下面
try
{
int _SeletedIndex = listBox.SelectedIndex();
listBox.Items.Remove(listBox.SelectedItems[0]);
people.RemoveAt(_SeletedIndex);
}
catch { }
You don't show where your code is to save, but I imagine there is one contact missing - probably the one under the contact you wanted to remove? 您没有显示代码的保存位置,但我想缺少一个联系人-可能是您要删除的联系人下面的那个联系人?
Since you are using SelectedIndex
AFTER removing the item from the list box, then some other item must be selected. 由于使用的是
SelectedIndex
之后从列表框中删除该项目,因此必须选择其他一些项目。
Try reversing the order: 尝试颠倒顺序:
private void btnRmv_Click(object sender, EventArgs e)
{
try
{
people.RemoveAt(listBox.SelectedIndex);
listBox.Items.Remove(listBox.SelectedItems[0]);
}
catch { }
}
You are removing selected item
first, so you lose the selected index and no item is deleted in list people
. 首先要删除
selected item
,所以丢失选定的索引,并且列表people
没有任何项目被删除。
Lets reorder the lines: 让我们重新排列行:
people.RemoveAt(listBox.SelectedIndex);
listBox.Items.Remove(listBox.SelectedItems[0]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.