winforms C# Listview中的检查项

hgb9j2n6  于 2023-06-24  发布在  C#
关注(0)|答案(3)|浏览(135)

我有一个C#应用程序中的Listview控件,其中填充了一些名称和复选框,以选择一个或多个值。除了点击复选框,用户还可以点击名称,它会变成蓝色。我想保留这个功能,因为点击名称会显示更多的数据,点击复选框会将其标记为进一步处理
我相信点击复选框会改变项目。选中属性并点击名称会改变项目。选中但似乎没有那么简单。
我有一个代码来计算检查的项目:

private void Listview1_ItemChecked(object sender, ItemCheckedEventArgs e) 
{
    foreach(ListViewItem Item in ListView1.Items) 
    {
        if (Item != null) 
        {
            if (Item.Checked == true) N++;
        }
    }
    Textbox1.Text = N.ToString();
}

当用户点击复选框时,会显示正确的数字,但当他点击名称时,即使仍有更多的复选框被选中,选中的数字也会变为1,这显然是错误的。同样,当窗体和控件加载时,即使没有选中复选框,我也会得到N=1。
我做错了什么?
编辑:感谢您的快速React和有用的提示!
我刚刚发现我的问题是我的疏忽,因为我忘记删除我的旧代码!:)起初我使用多个选择来拾取项目,然后我切换到复选框,但仍然调用SelectionChanged事件并修改文本框内容

c6ubokkw

c6ubokkw1#

若要获取ListView控件中选中项的数目,请使用ListView.CheckedItems.Count属性。
示例:

int numCheckedItems = myListView.CheckedItems.Count;

TextBox1.Text = myListView.CheckedItems.Count.ToString();
e0bqpujr

e0bqpujr2#

您不应该遍历所有项目,因为ItemCheckedEventArgs提供了您需要的所有信息:

private void Listview1_ItemChecked(object sender, ItemCheckedEventArgs e) 
{
    ListViewItem item = e.Item as ListViewItem;
    if (item != null)
    {
       if (item.Checked) 
       {
           N++;
       }  
       else
       {
           N--;
       }
    }
    Textbox1.Text = N.ToString();
}
vhmi4jdf

vhmi4jdf3#

private void saveButton_Click(object sender, EventArgs e)
{
   
    SelectEmployeeBLL selectEmployeeBLL = new SelectEmployeeBLL();

    int employeeId = Convert.ToInt32(employeeNameInsertComboBox.SelectedValue);
    
    int departmentId= Convert.ToInt32(departmentNameInsertComboBox.SelectedValue);

    bool departmentNameCheck = selectEmployeeBLL.DepartmentNameDuplicateCheck(departmentId, employeeId);

    if (departmentNameCheck)
    {
        MessageBox.Show("Department already have");
        return;
    }

    SelectEmployee selectEmployee = new SelectEmployee();
    selectEmployee.DepartmentIDID = departmentId;
    selectEmployee.EmployeeIDID = employeeId;
    

    bool aselectEmployee = selectEmployeeBLL.SelectEmployeeIsert(selectEmployee);
    if (aselectEmployee)
    {
        MessageBox.Show("save successfull");
        LoadEmployeeDepartment();
    }
}

相关问题