简体   繁体   English

C#设置在Winform中插入新项后选择的ListView项

[英]C# Set ListView item selected after inserting a new Item in winform

I've the following code that Clones/makes a copy the selected ListView item, removes the Selected item, and then re-inserts the copied Item in a new position in the ListView. 我有以下代码,用于克隆/复制选定的ListView项目,删除选定的项目,然后将复制的Item重新插入ListView中的新位置。

private void btnUp_Click(object sender, EventArgs e)
{
    if (listView1.SelectedItems.Count == 1)
    {
        int iIndex = listView1.FocusedItem.Index;

        if (iIndex > 0)
        {
            ListViewItem oListViewItem = (ListViewItem)listView1.FocusedItem.Clone();

            listView1.Items.Remove(listView1.FocusedItem);
            listView1.Items.Insert(iIndex - 1, oListViewItem);
        }
    }
}

The code works fine and the item is moved and the list updated. 该代码工作正常,并且该项目已移动并且列表已更新。 However, I'm wanting the newly inserted Item to remain selected. 但是,我希望新插入的项目保持选中状态。 I tried 我试过了

listView1.Items[iIndex - 1].Selected = true; listView1.Items [iIndex-1] .Selected = true;

but this doesn't have the desired affect. 但这并没有达到预期的效果。

What else can I try ? 我还能尝试什么?

If you add the Selected = true to the newly inserted item index then your code should work as expected. 如果将Selected = true添加到新插入的项目索引中,则您的代码应该可以按预期工作。 But when you click on the button, the focus goes to the pressed button and under the default properties the ListView.HideSelection is set to True. 但是,当您单击按钮时,焦点将移至按下的按钮上,并且在默认属性下, ListView.HideSelection设置为True。 So you don't see any item selected. 因此,您看不到任何选定的项目。 If you press TAB on your form until the ListView is again the focused control, your ListViewItem should be showed as selected. 如果在窗体上按TAB键直到ListView再次成为焦点控件,则ListViewItem应显示为选中状态。

If you want to show some form of (dimmed) selection even when the control is not focused then set 如果即使控件未聚焦也要显示某种形式的(变暗)选择,请设置

 listView1.HideSelection = false;

However, if I understand what you are trying to do (moveup an item) then you should change your code to use the SelectedItems[0] element instead of the FocusedItem 但是,如果我了解您要执行的操作(移动项目),则应更改代码以使用SelectedItems [0]元素而不是FocusedItem

if (listView1.SelectedItems.Count == 1)
{
    int iIndex = listView1.SelectedItems[0].Index;
    if (iIndex > 0)
    {
        ListViewItem oListViewItem = (ListViewItem)listView1.SelectedItems[0].Clone();
        listView1.SelectedItems[0].Remove();
        listView1.Items.Insert(iIndex -1, oListViewItem);
        listView1.Items[iIndex -1].Selected = true;
    }
}

You might want to try using the IndexOf method to get the index of the inserted item. 您可能想尝试使用IndexOf方法获取插入项的索引。

listView.Items[listView.Items.IndexOf(oListViewItem)].Selected = true;

Hope this helps. 希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM