C# 获取单个 listView SelectedItem

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15091400/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 14:01:32  来源:igfitidea点击:

Get single listView SelectedItem

c#winformslistviewitem

提问by topofsteel

I have the MultiSelectproperty of the listView set to false and I'm trying to get a single listViewItem. But the available property is SelectedItems. I've been using the following code...

MultiSelect将 listView的属性设置为 false,并且我正在尝试获取单个 listViewItem。但是可用的属性是SelectedItems. 我一直在使用以下代码...

foreach (ListViewItem item in listView1.SelectedItems)
{
    //do something with item.text or whatever
}

Because I know there will only be one item selected. What is the correct way of doing this?

因为我知道只会选择一项。这样做的正确方法是什么?

采纳答案by Vogel612

Usually SelectedItemsreturns either a collection, an array or an IQueryable.

通常SelectedItems返回一个集合、一个数组或一个IQueryable.

Either way you can access items via the index as with an array:

无论哪种方式,您都可以像使用数组一样通过索引访问项目:

String text = listView1.SelectedItems[0].Text; 

By the way, you can save an item you want to look at into a variable, and check its structure in the locals after setting a breakpoint.

顺便说一句,您可以将要查看的项目保存到变量中,并在设置断点后在 locals 中检查其结构。

回答by gzaxx

I do this like that:

我这样做:

if (listView1.SelectedItems.Count > 0)
{
     var item = listView1.SelectedItems[0];
     //rest of your logic
}

回答by Pedro Loureiro

Sometimes using only the line below throws me an Exception,

有时仅使用下面的行会引发异常,

String text = listView1.SelectedItems[0].Text; 

so I use this code below:

所以我在下面使用这个代码:

private void listView1_SelectedIndexChanged(object sender, EventArgs e) 
{ 
    if (listView1.SelectedIndices.Count <= 0) 
    { 
        return; 
    } 
    int intselectedindex = listView1.SelectedIndices[0]; 
    if (intselectedindex >= 0) 
    {
        String text = listView1.Items[intselectedindex].Text;

        //do something
        //MessageBox.Show(listView1.Items[intselectedindex].Text); 
    } 
}

回答by Vman

If its just a natty little app with one or two ListViewsI normally just create a little helper property:

如果它只是一个带有一两个的整洁的小应用程序,ListViews我通常只创建一个小助手属性:

private ListViewItem SelectedItem { get { return (listView1.SelectedItems.Count > 0 ? listView1.SelectedItems[0] : null); } }

If I have loads, then move it out to a helper class:

如果我有负载,则将其移至辅助类:

internal static class ListViewEx
{
    internal static ListViewItem GetSelectedItem(this ListView listView1)
    {
        return (listView1.SelectedItems.Count > 0 ? listView1.SelectedItems[0] : null);
    }
}

so:

所以:

ListViewItem item = lstFixtures.GetSelectedItem();

The ListViewinterface is a bit rubbish so I normally find the helper class grows quite quickly.

ListView接口是一个有点垃圾,所以我通常会找到的辅助类相当快的增长。

回答by Lulceltech

For a shopping cart situation here's what I recommend. I'm gonna break it down into it's simplest form.

对于购物车情况,这是我推荐的。我要把它分解成最简单的形式。

Assuming we start with this(a list view with 2 colums, 2 buttons, and a label): starting

假设我们从这个开始(一个带有 2 个列、2 个按钮和一个标签的列表视图): 开始

First things first, removing the items, to do that we'll enter our remove button:

首先,删除项目,为此我们将输入我们的删除按钮:

private void button2_Click(object sender, EventArgs e)
{
    listView1.Items.Remove(listView1.SelectedItems[0]);
    label1.Text = updateCartTotal().ToString();
}

Now the second line is updating our labels total using the next function i'll post to addup all the total of column 2 in the listview:

现在第二行是使用下一个函数更新我们的标签总数,我将发布以添加列表视图中第 2 列的所有总数:

private decimal updateCartTotal()
{
    decimal runningTotal = 0;
    foreach(ListViewItem l in listView1.Items)
    {
        runningTotal += Convert.ToDecimal(l.SubItems[1].Text);
    }
    return runningTotal;
}

You don't have to use decimal like I did, you can use float or int if you don't have decimals. So let's break it down. We use a for loop to total all the items in the column 2(SubItems[1].Text). Add that to a decimal we declared prior to the foreach loop to keep a total. If you want to do tax you can do something like:

你不必像我一样使用小数,如果你没有小数,你可以使用浮点数或整数。所以让我们分解它。我们使用 for 循环对列 2(SubItems[1].Text) 中的所有项目求和。将其添加到我们在 foreach 循环之前声明的小数以保持总数。如果您想纳税,您可以执行以下操作:

return runningTotal * 1.15;

or whatever your tax rate is.

或者不管你的税率是多少。

Long and short of it, using this function you can retotal your listview by just calling the function. You can change the labels text like I demo'd prior if that's what you're after.

总而言之,使用此函数,您只需调用该函数即可重新汇总您的列表视图。如果这是您所追求的,您可以像我之前演示的那样更改标签文本。

回答by vapcguy

None of the answers above, at least to me, show how to actually handle determining whether you have 1 item or multiple, and how to actually get the values out of your items in a generic way that doesn't depend on there actually only being one item, or multiple, so I'm throwing my hat in the ring.

至少对我而言,上面的答案都没有显示如何实际处理确定您是否有 1 个项目或多个项目,以及如何以不依赖于实际仅存在的通用方式从项目中实际获取值一项或多项,所以我把我的帽子扔进了戒指。

This is quite easily and generically done by checking your count to see that you have at least one item, then doing a foreachloop on the .SelectedItems, casting each item as a DataRowView:

通过检查您的计数以查看您至少有一个项目,然后在foreach上执行循环.SelectedItems,将每个项目转换为一个DataRowView

if (listView1.SelectedItems.Count > 0)
{
     foreach (DataRowView drv in listView1.SelectedItems)
     {
         string firstColumn = drv.Row[0] != null ? drv.Row[0].ToString() : String.Empty;
         string secondColumn = drv.Row[1] != null ? drv.Row[1].ToString() : String.Empty;
         // ... do something with these values before they are replaced
         // by the next run of the loop that will get the next row
     }
}

This will work, whether you have 1 item or many. It's funny that MSDN saysto use ListView.SelectedListViewItemCollectionto capture listView1.SelectedItemsand iterate through that, but I found that this gave an error in my WPF app: The type name 'SelectedListViewItemCollection' does not exist in type 'ListView'.

无论您有 1 个项目还是多个项目,这都行得通。MSDN 说用来ListView.SelectedListViewItemCollection捕获listView1.SelectedItems和迭代它很有趣,但我发现这在我的 WPF 应用程序中给出了一个错误: The type name 'SelectedListViewItemCollection' does not exist in type 'ListView'.

回答by Nikola

This works for single as well as multi selection list:

这适用于单选和多选列表:

foreach (ListViewItem item in listView1.SelectedItems)
{
    int index = ListViewItem.Index;
    //index is now zero based index of selected item
}

回答by TaTa

foreach (ListViewItem itemRow in taskShowListView.Items)
{
    if (itemRow.Items[0].Checked == true)
    {
        int taskId = Convert.ToInt32(itemRow.SubItems[0].Text);

        string taskDate = itemRow.SubItems[1].ToString();
        string taskDescription = itemRow.SubItems[2].ToString();            
    }
}

回答by Stefan27

If you want to select single listview item no mouse click over it try this.

如果您想选择单个列表视图项目,请不要在其上单击鼠标,请尝试此操作。

private void timeTable_listView_MouseUp(object sender, MouseEventArgs e)
        {
            Point mousePos = timeTable_listView.PointToClient(Control.MousePosition);
            ListViewHitTestInfo hitTest = timeTable_listView.HitTest(mousePos);



            try
            {
            int columnIndex = hitTest.Item.SubItems.IndexOf(hitTest.SubItem);
            edit_textBox.Text = timeTable_listView.SelectedItems[0].SubItems[columnIndex].Text;
            }
            catch(Exception)
            {

            }



        }