代码之家  ›  专栏  ›  技术社区  ›  XstreamINsanity

如何编辑选中列表框中项目的名称?

  •  1
  • XstreamINsanity  · 技术社区  · 16 年前

    我有一个有x个项目的 checkedlistbox 这些项目在运行时放在那里。这些项目应该表示可以在 DataGridView 中显示的报告。我现在需要做的是在报告名称旁边的括号中显示每个报告的记录计数。我试着编辑这个项目的实际名称,但没能找到怎么做。所以,我残忍地强迫它。将项目保存到数组中,清除项目,将记录计数附加到数组中的每个项目,创建新项目。嗯,这导致了问题,因为现在它没有保留我的支票,原因是,每当我生成报告时,我都会清除项目并重新创建它们。好吧,除了执行另一个 foreach loop以保存选中的状态,是否有人知道如何更改a checkedlistbox中现有项的文本?

    这是我目前拥有的代码:

    在mainform.designer.cs中:

    this.clbreports.items.addrange(new object[]){
    “报告1”,
    “报告2”,
    “报告3”,
    “报告4”,
    “报告5”,
    “报告6”,
    “报告7”,
    “报告8”,
    “报告9”,
    “报告10”,
    “报告11”};
    < /代码> 
    
    

    看起来:

    我希望它看起来像(但不会全部是0):。

    下面是selectedIndexChanged函数:

    private void clbreports_selectedIndexChanged(object sender,eventargs e)
    {
    string strcheckbox=clbreports.selectedItem.toString();
    bool bshowallischeck=clbreports.getitemchecked(clbreports.findstring(“显示所有错误报告”));
    bool bselected=clbreports.getitemchecked(clbreports.findstring(strcheckbox));
    int nindex=-1;
    
    if(strcheckbox.contains(“显示所有错误报告”))
    {
    foreach(字符串str-in-strreports)
    {
    如果(!)str.contains(“显示所有错误报告”)&!str.contains(“显示标记的记录”))
    {
    nindex=clbreports.findstring(str);
    如果(nindex>-1)
    {
    clbreports.setitemchecked(nindex,bselected);
    }
    }
    }
    }
    其他的
    {
    if(strcheckbox.contains(“显示所有错误报告”)bshowallischeck)
    {
    foreach(字符串str-in-strreports)
    {
    nindex=clbreports.findstring(str);
    如果(nindex>-1)
    {
    clbreports.setitemchecked(nindex,false);
    }
    }
    }
    
    nindex=clbreports.findstring(strcheckbox);
    如果(nindex>-1)
    {
    clbreports.setitemchecked(nindex,bshowallischeck?正确:b选择);
    }
    }
    
    string[]strcheckeditems=新字符串[clbreports.checkeditems.count];
    clbreports.checkeditems.copyto(strcheckeditems,0);
    list<string>复选框reportfilter=新列表<string>();
    foreach(本文档中的reportrecord obj)。
    {
    foreach(strcheckeditems中的字符串str)
    {
    if(str.contains(obj.description))。
    {
    复选框reportfilter.add(obj.partid.toString());
    }
    }
    }
    尝试
    {
    if(复选框reportfilter.count==0&clbreports.checkeditems.count>0)
    {
    引发新的NullReferenceException();
    }
    
    _ strReportfilter=string.join(“,”,checkboxReportfilter.toArray());
    }
    catch(空引用异常)
    {
    _ strReportFilter=“-1”;
    }
    
    GenerateReport();
    }
    < /代码> 
    
    

    下面是我清除项目、获取报告计数和创建新项目的代码。

    \lstreatrecords=\u datacontroller.reportlist;
    bool[]bchecked=new bool[clbreports.items.count];
    int计数器=0;
    foreach(字符串str-in-strreports)
    {
    foreach(clbreports.selecteditems中的字符串str2)
    {
    bchecked[ncounter]=str2.contains(str);
    }
    nCalp++;
    }
    
    clbreports.items.clear();
    n计数器=0;
    
    foreach(字符串str-in-strreports)
    {
    int ncount=&ultsreportrecords.where<reportrecord>(委托(reportrecord rr){
    返回rr.description==str;
    };
    
    string newreport=str+“(”+ncount+“)”;
    clbreports.items.add(newreport);
    clbreports.setitemchecked(ncounter,bchecked[ncounter]);
    nCalp++;
    }
    < /代码> 
    
    

    请告诉我有一个更简单的方法。我尝试通过clbreports.items执行foreach循环,但它希望我将其强制转换为字符串(尝试强制转换为复选框时出错),因此我无法更改值。即使我可以将它强制转换为一个复选框,我也有一种感觉,它会给我一个错误,那就是枚举失败是因为列表被更改了(或者不管他们怎么说)。欢迎提供任何帮助。谢谢,

    编辑:Please know that the report x are just so that the actual report names are not displayed to keep it generic.但是,在代码中,我只是复制和粘贴了,因此显示所有错误报告和显示所有标记的记录都是我需要检查的报告。DataGridView. 我现在需要做的是在报告名称旁边的括号中显示每个报告的记录计数。我试着编辑这个项目的实际名称,但没能找到怎么做。所以,我残忍地强迫它。将项目保存到数组中,清除项目,将记录计数附加到数组中的每个项目,创建新项目。嗯,这导致了问题,因为现在它没有保留我的支票,原因是,每当我生成报告时,我都会清除项目并重新创建它们。好吧,而不是做另一件事foreach循环以保存选中状态,是否有人知道如何更改复选列表框?

    这是我目前拥有的代码:

    在mainform.designer.cs中:

    this.clbReports.Items.AddRange(new object[] {
    "Report 1",
    "Report 2",
    "Report 3",
    "Report 4",
    "Report 5",
    "Report 6",
    "Report 7",
    "Report 8",
    "Report 9",
    "Report 10",
    "Report 11"});
    

    看起来:

    alt text

    我希望它看起来像(但不会都是0的):

    alt text

    下面是selectedIndexChanged函数:

    private void clbReports_SelectedIndexChanged(object sender, EventArgs e)
    {
        string strCheckBox = clbReports.SelectedItem.ToString();
        bool bShowAllIsChecked = clbReports.GetItemChecked(clbReports.FindString("Show All Error Reports"));
        bool bSelected = clbReports.GetItemChecked(clbReports.FindString(strCheckBox));
        int nIndex = -1;
    
        if (strCheckBox.Contains("Show All Error Reports"))
        {
            foreach (string str in _strReports)
            {
                if (!str.Contains("Show All Error Reports") && !str.Contains("Show Tagged Records"))
                {
                    nIndex = clbReports.FindString(str);
                    if (nIndex > -1)
                    {
                        clbReports.SetItemChecked(nIndex, bSelected);
                    }
                }
            }
        }
        else
        {
            if (strCheckBox.Contains("Show All Error Reports") || bShowAllIsChecked)
            {
                foreach (string str in _strReports)
                {
                    nIndex = clbReports.FindString(str);
                    if (nIndex > -1)
                    {
                    clbReports.SetItemChecked(nIndex, false);
                    }
                }
            }
    
            nIndex = clbReports.FindString(strCheckBox);
            if (nIndex > -1)
            {
                clbReports.SetItemChecked(nIndex, bShowAllIsChecked ? true : bSelected);
            }
        }
    
        string[] strCheckedItems = new string[clbReports.CheckedItems.Count];
        clbReports.CheckedItems.CopyTo(strCheckedItems, 0);
        List<string> checkBoxReportFilter = new List<string>();
        foreach (ReportRecord obj in this._lstReportRecords)
        {
            foreach (string str in strCheckedItems)
            {
                if (str.Contains(obj.Description))
                {
                    checkBoxReportFilter.Add(obj.PartID.ToString());
                }
            }
        }
        try
        {
            if (checkBoxReportFilter.Count == 0 && clbReports.CheckedItems.Count > 0)
            {
                throw new NullReferenceException();
            }
    
            _strReportFilter = String.Join(",", checkBoxReportFilter.ToArray());
        }
        catch (NullReferenceException)
        {
            _strReportFilter = "-1";
        }
    
        generateReport();
    }
    

    这里是代码,我在这里清除项目,获取报告计数和创建新项目。

    _lstReportRecords = _dataController.ReportList;
    bool[] bChecked = new bool[clbReports.Items.Count];
    int nCounter = 0;
    foreach (string str in _strReports)
    {
        foreach (string str2 in clbReports.SelectedItems)
        {
            bChecked[nCounter] = str2.Contains(str);
        }
        nCounter++;
    }
    
    clbReports.Items.Clear();
    nCounter = 0;
    
    foreach (string str in _strReports)
    {
        int nCount = _lstReportRecords.Where<ReportRecord>(delegate(ReportRecord rr) {
            return rr.Description == str;
        }).Count();
    
        string newReport = str + " (" + nCount + ")";
        clbReports.Items.Add(newReport);
        clbReports.SetItemChecked(nCounter, bChecked[nCounter]);
        nCounter++;
    }
    

    请告诉我有一个更简单的方法。我尝试通过clbreports.items执行foreach循环,但它希望我将其强制转换为字符串(尝试强制转换为复选框时出错),因此我无法更改值。即使我可以将它强制转换为一个复选框,我也有一种感觉,它会给我一个错误,那就是枚举失败是因为列表被更改了(或者不管他们怎么说)。欢迎提供任何帮助。谢谢。

    编辑:请注意,报表X只是为了不显示实际的报表名称以保持其通用性。但是,在代码中,我只是复制和粘贴,所以显示所有错误报告和显示所有标记的记录都是我需要检查的报告。

    4 回复  |  直到 9 年前
        1
  •  1
  •   Sebastian Edelmeier    16 年前

    如果我是你,我会尝试让inotifyPropertiesChanged接口运行起来。 除非必要,否则你不应该把事情搞得一团糟。这意味着您不能使用设计器创建项,但据我所知,它是一个运行时修改的列表…

    详细地说:

    创建一个实现inotifyPropertiesChanged的类(例如“foo”)(基本上这将告诉任何侦听器文本属性已更改)。此类将保存所有条目的名称。

    创建一个ObservableCollection并将选中的列表框绑定到该集合。在WinForms中,您必须创建一个数据绑定源,并将集合插入一端,将组合框插入另一端。

    对集合所做的任何更改都将在控件中可见。

    高温高压 塞比

        2
  •  1
  •   sh code    9 年前

    正确的(==最简单和最直接的)答案和解决方案是:

    this.clbReports.Items[nIndex] = "new text of the item"
    

    是的,这些项目属于“对象”类型。不,没人介意,字符串也是一个对象;)

        3
  •  0
  •   Jocelyn    16 年前

    要更改列表框(或选中的列表框)中的项目,应更改这些项目' ToString() 结果。

    最简单的解决方案是创建一个“holder”类,它引用了它所代表的报告。那么holder类的toString()方法应该如下所示:

    public override string ToString()
    {
       return String.Format("{0} ({1})", BaseStr, MyReport.RecordCount);
    }
    

    如果你改变 MyReport.RecordCount 不知何故(因为报表的记录计数发生了变化),您可以调用 clbReports.Refresh() ,它将自动显示新值。

    我认为这样您甚至不需要第二个代码块中的临时数组解决方案;但是,我想建议另一种方法来获取项的检查状态。 您可以迭代 clbReports.CheckedIndices 填满你的 bChecked 数组与 true 值仅用于该数组中的索引。

        4
  •  0
  •   XstreamINsanity    16 年前

    嗯,由于时间限制,我尝试了别的方法。我使用了一个listView,其中checkbox=true和view=list。我还删除了“显示所有错误报告”和“在列表外的复选框中显示标记的记录”。这使得实现我想要的功能更加容易。这是新密码。

    主窗体.designer.cs

        // 
        // cbTaggedRecords
        // 
        this.cbTaggedRecords.AutoSize = true;
        this.cbTaggedRecords.Location = new System.Drawing.Point(151, 9);
        this.cbTaggedRecords.Name = "cbTaggedRecords";
        this.cbTaggedRecords.Size = new System.Drawing.Size(106, 17);
        this.cbTaggedRecords.TabIndex = 3;
        this.cbTaggedRecords.Text = "Tagged Records";
        this.cbTaggedRecords.UseVisualStyleBackColor = true;
        this.cbTaggedRecords.CheckedChanged += new System.EventHandler(this.ShowTaggedRecords_CheckChanged);
        // 
        // cbAllErrorReports
        // 
        this.cbAllErrorReports.AutoSize = true;
        this.cbAllErrorReports.Location = new System.Drawing.Point(6, 9);
        this.cbAllErrorReports.Name = "cbAllErrorReports";
        this.cbAllErrorReports.Size = new System.Drawing.Size(102, 17);
        this.cbAllErrorReports.TabIndex = 2;
        this.cbAllErrorReports.Text = "All Error Reports";
        this.cbAllErrorReports.UseVisualStyleBackColor = true;
        this.cbAllErrorReports.CheckedChanged += new System.EventHandler(this.ShowAllErrorReports_CheckChanged);
        // 
        // listView1
        // 
        this.listView1.CheckBoxes = true;
        listViewItem1.StateImageIndex = 0;
        listViewItem2.StateImageIndex = 0;
        listViewItem3.StateImageIndex = 0;
        listViewItem4.StateImageIndex = 0;
        listViewItem5.StateImageIndex = 0;
        listViewItem6.StateImageIndex = 0;
        listViewItem7.StateImageIndex = 0;
        listViewItem8.StateImageIndex = 0;
        listViewItem9.StateImageIndex = 0;
        this.listView1.Items.AddRange(new System.Windows.Forms.ListViewItem[] {
        listViewItem1,
        listViewItem2,
        listViewItem3,
        listViewItem4,
        listViewItem5,
        listViewItem6,
        listViewItem7,
        listViewItem8,
        listViewItem9});
        this.listView1.Location = new System.Drawing.Point(6, 29);
        this.listView1.Name = "listView1";
        this.listView1.Size = new System.Drawing.Size(281, 295);
        this.listView1.TabIndex = 1;
        this.listView1.UseCompatibleStateImageBehavior = false;
        this.listView1.View = System.Windows.Forms.View.List;
        this.listView1.ItemChecked += new System.Windows.Forms.ItemCheckedEventHandler(this.listView_ItemChecked);
    

    主要形式

        private void listView_ItemChecked(object sender, ItemCheckedEventArgs e)
        {
            if (e != null)
            {
                int nLength = e.Item.Text.IndexOf("(") - 1;
                string strReport = nLength <= 0 ? e.Item.Text : e.Item.Text.Substring(0, nLength);
                if (e.Item.Checked)
                {
                    _lstReportFilter.Add(strReport);
                }
                else
                {
                    _lstReportFilter.Remove(strReport);
                }
            }
    
            List<string> checkBoxReportFilter = new List<string>();
            foreach (ReportRecord obj in this._lstReportRecords)
            {
                foreach (string str in _lstReportFilter)
                {
                    if (str.ToLower().Contains(obj.Description.ToLower()))
                    {
                        checkBoxReportFilter.Add(obj.PartID.ToString());
                    }
                }
            }
            try
            {
                if (checkBoxReportFilter.Count == 0 && listView1.CheckedItems.Count > 0)
                {
                    throw new NullReferenceException();
                }
    
                _strReportFilter = String.Join(",", checkBoxReportFilter.ToArray());
            }
            catch (NullReferenceException)
            {
                _strReportFilter = "-1";
            }
    
            if (!bShowAll)
            {
                generateReport();
            }
        }
    
        private void ShowAllErrorReports_CheckChanged(object sender, EventArgs e)
        {
            bShowAll = true;
            foreach (ListViewItem lvi in listView1.Items)
            {
                lvi.Checked = ((CheckBox)sender).Checked;
            }
    
            _lstReportFilter.Clear();
            bShowAll = false;
            generateReport();
        }
    
        private void ShowTaggedRecords_CheckChanged(object sender, EventArgs e)
        {
            bool bChecked = ((CheckBox)sender).Checked;
            if (bChecked)
            {
                if (!_lstReportFilter.Contains("Show Tagged Records"))
                {
                    _lstReportFilter.Add("Show Tagged Records");
                }
            }
            else
            {
                _lstReportFilter.Remove("Show Tagged Records");
            }
    
            listView_ItemChecked(null, null);
        }
    

    向复选框添加计数的代码

                _lstReportRecords = _dataController.ReportList;
    
                int nTotalCount = 0;
    
                foreach (ListViewItem lvi in listView1.Items)
                {
                    int nCount = _lstReportRecords.Where(rr => lvi.Text.Contains(rr.Description)).Count();
                    nTotalCount += nCount;
                    lvi.Text = (lvi.Text.Contains("(") ? lvi.Text.Substring(0, lvi.Text.IndexOf("(") + 1) : lvi.Text + " (") + nCount.ToString() + ")";
                }
    
                cbAllErrorReports.Text = (cbAllErrorReports.Text.Contains("(") ? cbAllErrorReports.Text.Substring(0, cbAllErrorReports.Text.IndexOf("(") + 1) : cbAllErrorReports.Text + " (") + nTotalCount.ToString() + ")";
                int nTaggedCount = _lstReportRecords.Where(rr => rr.Description.Contains("Tagged")).Count();
                cbTaggedRecords.Text = (cbTaggedRecords.Text.Contains("(") ? cbTaggedRecords.Text.Substring(0, cbTaggedRecords.Text.IndexOf("(") + 1) : cbTaggedRecords.Text + " (") + nTaggedCount.ToString() + ")";
    

    感谢大家的帮助和想法。

    推荐文章