C#listview复选框

时间:2014-03-23 10:09:40

标签: c# listview checkeditems

我正在尝试获取刚刚被检查的listview项的索引,并根据刚检查的项目更新数据库,而不考虑之前检查过的其他项目 我试图使用复选框来指示用户是否想要通知,因此当用户选中该复选框时,我想使用该项的索引并将该项的通知设置为true但我只能获得所有的签到项索引一次。

请帮助。

我能够调用itemcheck事件函数,但它会考虑最初检查的项目以及用户检查的项目。 我设法使用布尔函数“Item_checked by user”分隔最初检查的项目

 ` private static bool checked_by_user;
    private void courseworks_ItemCheck(object sender, ItemCheckEventArgs e)
    {
        if (checked_by_user == true)
        { //do something
        }
        else ;//do nothing

    }`

现在,我希望能够仅使用刚刚检查过的行的bar_ref_id,我的列表视图是从数据库创建的,如下所示

foreach (var item2 in CW_query2)//for each CW
            {
                if (item.Status == true)
                {
                    ListViewItem items = new ListViewItem(new[] {//adds items into list view, per column
                    item2.Module_Code, item2.Title, item2.Due_Date.ToString("dd/MM/yy"),"Submitted",item.Bar_Ref_ID
                });
                    courseworks.Items.Add(items);
                }
                else
                {
                    ListViewItem items = new ListViewItem(new[] {//adds items into list view, per column
                    item2.Module_Code, item2.Title, item2.Due_Date.ToString("dd/MM/yy"),"Not-Submitted",item.Bar_Ref_ID
                });
                    courseworks.Items.Add(items);

                }

我希望我添加的信息有所帮助。 提前致谢

1 个答案:

答案 0 :(得分:0)

如果您已经从数据库中获取订阅并根据用户的订阅设置每个项目的Checked属性,那么最简单的方法是使用复选框' CheckedChanged事件?很难说出你的实现可能是什么,但你应该能够在取消选中该框时取消一个功能(删除订阅),以及选中该框时的另一个功能(添加订阅)。

如果您能够提供一些代码,我可能会更具体。

更具体

在您的ItemChecked事件中,.NET公开object senderItemCheckEventArgs e作为事件的参数。在该函数中,您可以查看sender以获取已选中/未选中的ListViewItem,并且可以查看e以检索ListView中该项的索引(如果可以的话)使用索引轻松更改数据库中的数据)。这是一个简短的例子,我几乎偷了straight from Microsoft

private void ListView1_ItemCheck1(object sender, ItemCheckEventArgs e)
{
    ListViewItem item = (ListViewItem)sender

    if (e.CurrentValue==CheckState.Unchecked)
    {
        Unsubscribe(e.Index, currentUserID);
          /*You can pass the Index of the ListViewItem that caused the event
          to a method that will update your database (I would find it easier
          to program a function that takes the current user's ID as a parameter)*/

        Unsubscribe(item.Name, currentUserID);
          /*OR this might be a better way for you to reference what subscription
          should be cancelled (again, in addition to a UserID)*/
    }
    else if((e.CurrentValue==CheckState.Checked))
    {
        Subscribe(e.Index, currentUserID);
    }
}

private void Unsubscribe(int index, int userID)
{
    //unsubscribe the referenced userID from the subscription at index
}

private void Unsubscribe(string subscriptionName, int userID)
{
    //unsubscribe the referenced userID from the subscription called subscriptionName
}

我无法为您的第二段代码提供更具体的示例,因为我不太确定它在做什么。看起来您可能正在做一些比上面的代码示例更复杂的事情,但代码可能会帮助您。