C# 如何将选中项移动到列表框
我目前正在开发一个清单程序,我想将新选中的C# 如何将选中项移动到列表框,c#,winforms,C#,Winforms,我目前正在开发一个清单程序,我想将新选中的CheckedListBox项目移动到一个正常的ListBox,但是CheckedListBox中的项目不会被销毁,当您再次取消选中该项目时,它只会将文本添加到正常的ListBox 我已经尝试使用foreach语句获取CheckedListBox中的所有选中项 private void TaskBox_ItemCheck(object sender, ItemCheckEventArgs e) { if(taskBox.CheckedItems
CheckedListBox
项目移动到一个正常的ListBox
,但是CheckedListBox
中的项目不会被销毁,当您再次取消选中该项目时,它只会将文本添加到正常的ListBox
我已经尝试使用foreach
语句获取CheckedListBox
中的所有选中项
private void TaskBox_ItemCheck(object sender, ItemCheckEventArgs e)
{
if(taskBox.CheckedItems != null)
{
foreach (object itemChecked in taskBox.CheckedItems)
{
string s = taskBox.GetItemCheckState(taskBox.Items.IndexOf(itemChecked)).ToString();
fTaskBox.Items.Add(s);
taskBox.Items.Remove(s);
}
}
}
问题在于
CheckedListBox
上的ItemCheck
事件在项目的CheckState
实际更改之前触发。这意味着在循环时,刚刚单击的项目尚未添加到CheckedItems
列表中。它在第二次单击时起作用,因为在第一次单击时选中的项目在该点处位于CheckedItems
列表中,并在循环中拾取
解决此问题的一个简单方法是使用MouseUp
事件。如果循环检查checkedDices
而不是CheckedItems
,则不需要额外的代码来计算选中项的索引。这应该做到:
private void TaskBox_MouseUp(object sender, MouseEventArgs e)
{
foreach (int index in taskBox.CheckedIndices)
{
fTaskBox.Items.Add(taskBox.Items[index]);
taskBox.Items.RemoveAt(index);
}
}
你应该养成同时使用google和-Aslo的习惯:你到底为什么要把索引变成字符串??它可用于使用RemoveAt删除项目。为什么要为你的信息添加索引而不是项目文本?我使用了google和msdn。我在multible网站上查找了这个问题,但每个解决方案都有相同的问题:它只在选中项目后才将其删除,然后再次取消选中。