C#:如何确保在执行操作之前在 ListView 中选择了行或项目?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/817294/
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-05 02:21:50  来源:igfitidea点击:

C#: How do you make sure that a row or item is selected in ListView before performing an action?

c#.netwinforms

提问by

What is the best way to check if there is atleast a selected item in a listview or not in an if statement?

检查列表视图中是否至少有一个选定项目或在 if 语句中没有的最佳方法是什么?

采纳答案by JaredPar

I'm not entirely sure what you are asking. Do you want to make sure at least 1 item is selected before running an action? If so the following should work

我不完全确定你在问什么。是否要确保在运行操作之前至少选择了 1 个项目?如果是这样,以下应该有效

if ( listView.SelectedItems.Count > 0 ) { 
  // Do something
}

Or are you curious if a particular item is selected? If so try the following

或者您是否好奇是否选择了特定项目?如果是这样,请尝试以下操作

if ( listView.SelectedItems.Contains(someItem)) { 
  // Do something
}

回答by Winston Smith

if( listView.SelectedItems.Count > 0 ){
 // do stuff here
}

回答by Louie Bacaj

You can also check the value of a selected item or perhaps bind it to a string if needed:

您还可以检查所选项目的值,或者根据需要将其绑定到字符串:

        //Below is with string
        String member = (String)ListView1.SelectedValue;

        //Below is with any class
        AnyClass member = (AnyClass)ListView1.SelectedValue;
        String StaffID = member.StaffID;

回答by Ahmad Al-taher

//Here a simple loop that go through all the items in the list  

for (int i = 0; i < listView1.Items.Count; i++)
{
    //checks if the item in the list has the value true to the properties checked 

    if (listView1.Items[x].Checked == true)
    {//your  code
        //e.g. 
        listView1.Items[x].Checked = false;
    }
}

回答by hetuka kodekar

You can also check count of the selected item list by using getCheckedItemCount() method of the listview. for example,

您还可以使用列表视图的 getCheckedItemCount() 方法检查所选项目列表的计数。例如,

if( listview.getCheckedItemCount() > 0 ) {

如果(listview.getCheckedItemCount()> 0){

 // do stuff here 

}

}

回答by TaTa

int taskId = Convert.ToInt32(itemRow.SubItems[0].Text);

int taskId = Convert.ToInt32(itemRow.SubItems[0].Text);

string taskDate = itemRow.SubItems1.ToString();

string taskDate = itemRow.SubItems 1.ToString();

string taskDescription = itemRow.SubItems[2].ToString();enter image description here

string taskDescription = itemRow.SubItems[2].ToString(); 在此处输入图片说明