在listview C#中添加包含现有项目的新项目

时间:2012-10-10 06:53:25

标签: c# winforms listview

我的listView中已经存在一些项目。页面上有一个添加按钮,用于打开一个对话框,用户可以在其中添加新项目。对话框关闭后,我必须附加已有现有项目的新项目。这是代码,直到结束,但没有添加新项目。我的列表视图中有多列。我在这方面做错了。

public frmEditObject(AddException ObjException)
{
    InitializeComponent();
    if (ObjException != null)
    {
        ListViewItem lviMember, lviSender = null;
        bool alreadyExists =
            exceptionsList.Find(
                item =>
                item.UserDetail == ObjException.UserDetail && item.ExceptionType != ObjException.ExceptionType) !=
            null
                ? true
                : false;
        if (!alreadyExists)
        {
            exceptionsList.Add(ObjException);
            lvwExceptionMember.Items.Clear();
            lvwExceptionMember.BeginUpdate();
            foreach (var item in exceptionsList)
            {
                if (item.ExceptionType == Enumerations.ExceptionType.Members)
                {
                    lviMember = new ListViewItem(
                        item.UserDetail);
                    lviMember.Tag = 0;
                    lviMember.SubItems.Add(GetDisplayNameFromSamAccountName(item.UserDetail));

                    lvwExceptionMember.Items.Add(lviMember);

                }
            }
            lvwExceptionMember.EndUpdate();
            lvwExceptionMember.Refresh();
        }
    }
}

1 个答案:

答案 0 :(得分:0)

请按照以下步骤操作:

public frmEditObject(AddException ObjException)
{
    InitializeComponent();

    //CHECK THAT YOUR OBJECT IS ALIVE
    if (ObjException != null)
    {
        ListViewItem lviMember, lviSender = null;
        bool alreadyExists = exceptionsList.Find(item => item.UserDetail == ObjException.UserDetail && item.ExceptionType != ObjException.ExceptionType) != null ? true : false;
        if (!alreadyExists)
        {
             //CHECK THAT NEW ITEM IS REALLY NEW, DOES NOT EXIST IN LIST
             exceptionsList.Add(ObjException);

             //YOU DO NOT NEED TO CLEAR LIST AND ADD ALL ITEMS TO IT
             //lvwExceptionMember.Items.Clear();


             //lvwExceptionMember.BeginUpdate();

                 Debug.WriteLine(item.ExceptionType);                 
                 if (item.ExceptionType == Enumerations.ExceptionType.Members)
                 {
                      //CHECK DOES YOUR OBJECT HAVE MEMBERS TYPE
                      lviMember = new ListViewItem(item.UserDetail);
                      lviMember.Tag = 0;
                      lviMember.SubItems.Add(GetDisplayNameFromSamAccountName(item.UserDetail));

                      lvwExceptionMember.Items.Add(lviMember);

                 }

            // lvwExceptionMember.EndUpdate();
            //lvwExceptionMember.Refresh();
        }
   }
}