【问题标题】:Winform How to increment items in a list [duplicate]Winform如何增加列表中的项目[重复]
【发布时间】:2016-11-19 17:34:52
【问题描述】:

我是一般编程的新手,从 C# 开始。有人告诉我,只需通过转换和解析就可以在不使用任何数组的情况下将项目添加到列表框中。但是我似乎无法让我的代码工作,我试图在将项目添加到 lisbox 时增加索引中的数字。

        if (this.index < MAX_ITEMS) // MAX_ITEMS or 10 
        {
            Convert.ToInt32(lstHoldValue.Items.Count);
            // here about splitting strings as per SA's comment but  may need to consider that
            int dnum;
            if (int.TryParse(txtInitialise.Text, out dnum))
            {
               (lstHoldValue.Items[this.index++]) = dnum;  //index is  incremented immediately after it is used 
                txtInitialise.Text = "";

                lstHoldValue.Items.Clear();
                for (int i = 0; i <= MAX_ITEMS; i++)
                {
                    if (i < index)
                    {
                        if (radSorted.Checked == true)
                        {

                            lstHoldValue.Items.Insert(0, "\t" + Convert.ToInt32(lstHoldValue.Items[i]));//show array in a listbox 
                            sorted();
                        }  

                  }

【问题讨论】:

    标签: c# winforms indexoutofboundsexception


    【解决方案1】:

    我假设您在第一个循环中遇到此错误。您正在尝试访问

    lstHoldValue.Items[this.index++] //index is 0 now
    

    但现在 lstHoldValue.Items 中没有项目,但仍尝试使用索引器访问它。怎么样:

    lstHoldValue.Items.Add(dnum);
    index++;
    

    对于重复检查,使用以下方法可能是一个更好的主意:

    bool isContained lstHoldValue.Items.Contains(possibleDuplicate); //possibleDuplicate is object
    

    代码建议

    //Get text inside text box
    string textInsideTheTextbox = textBox1.Text;
    //Dummy number
    int dnum;
    //Try parse
    if (int.TryParse(textInsideTheTextbox, out dnum) == false) { /*Can not parse*/return; }
    //Check duplicate
    bool isDuplicate = listBox1.Items.OfType<int>().Contains(dnum);
    //Show message box
    if(isDuplicate) { MessageBox.Show("This number already exists!"); return; }
    if(this.index < MAX_ITEMS) {
        //......
        //......
        //STUFF
        listBox1.Items.Add(dnum);
        index++;
        //......
        //......
        //STUFF
    }
    

    【讨论】:

    • 非常感谢!你是救生员:)
    • 但现在不再检查是否重复
    • 我没有彻底检查你的代码,但是在添加任何项目之前会进行重复检查,所以我认为重复的代码保持原样。
    • 我已经编辑了答案请检查
    • 谢谢你,我们应该成为朋友!!!
    猜你喜欢
    • 1970-01-01
    • 2010-11-28
    • 2019-05-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-16
    • 2014-05-28
    • 1970-01-01
    相关资源
    最近更新 更多