C# Windows窗体Listview所选项目

C# Windows forms Listview selected item
2021-09-14
  •  译文(汉语)
  •  原文(英语)

我在Windows表单中有一个由SQL数据库填充的listview.我有一个按钮,可以在选择记录时将其删除,并且工作正常.但是,如果没有选定的项目,并且我单击删除按钮,则会出现错误.所以我添加了一个消息框和一个条件,但始终获取-对象引用未设置为对象的实例.

所以我该如何检查列表视图中是否有选定的项目,以便它输入If?

谢谢

private void btnDelete_Click(object sender, EventArgs e)
    {

        bool b = this.lvBrands.FocusedItem.Checked;

        if (b == false)
        {
            MessageBox.Show("You must select a brand .", "Brand Select Error",
            MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
        }
        else
        {
            string sID = this.lvBrands.FocusedItem.Text;
            deleteBrand(sID);
            clearBrand(); 

        }    
解决过程1

你可以做

if(lvBrands.SelectedItems.Count > 0)
{
//you have something selected
}
解决过程2

FocusedElement在尝试引用它之前,需要检查是否不为null.

 bool b = false;
 if(this.lvBrands.FocusedItem != null)
 {
      b = this.lvBrands.FocusedItem.Checked;
 }

但是,正如@bobek指出的那样,如果您要查找选定的项目,则应使用SelectedItem而不是FocusedItem属性.只是使用,代码是相同的SelectedItem.

I have a listview in Windows forms populated by a SQL database. i have a button to delete records when selected and it's working fine. but if there is no selected item and i click the delete button i get and error. so i add a messagebox and a condition but a always get - Object reference not set to an instance of an object.

so how do i check if there is a selected item in the listview so it enter the If?

thanks

private void btnDelete_Click(object sender, EventArgs e)
    {

        bool b = this.lvBrands.FocusedItem.Checked;

        if (b == false)
        {
            MessageBox.Show("You must select a brand .", "Brand Select Error",
            MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
        }
        else
        {
            string sID = this.lvBrands.FocusedItem.Text;
            deleteBrand(sID);
            clearBrand(); 

        }    
Solutions1

You can do

if(lvBrands.SelectedItems.Count > 0)
{
//you have something selected
}
Solutions2

You need to check whether FocusedElement is not null before attempting to reference it.

 bool b = false;
 if(this.lvBrands.FocusedItem != null)
 {
      b = this.lvBrands.FocusedItem.Checked;
 }

However, as @bobek pointed out if you are looking for the selected item you should be using the SelectedItem instead of the FocusedItem property. The code would be the same, just using SelectedItem.

转载于:https://stackoverflow.com/questions/15576986/c-sharp-windows-forms-listview-selected-item

本人是.net程序员,因为英语不行,使用工具翻译,希望对有需要的人有所帮助
如果本文质量不好,还请谅解,毕竟这些操作还是比较费时的,英语较好的可以看原文

留言回复
我们只提供高质量资源,素材,源码,坚持 下了就能用 原则,让客户花了钱觉得值
上班时间 : 周一至周五9:00-17:30 期待您的加入