ListBox没有更新SelectedItems

4

我正在为一项学校练习编写代码,以下是我的代码:

private void button1_Click(object sender, EventArgs e)
{
    List<int> lista = new List<int>();
    int delivi = 0;
    int brojac = 0;

    listBox1.BeginUpdate();
    foreach (string s in listBox1.Items)
    {
        int broj = int.Parse(s);
        int delenje_so = int.Parse(textBox1.Text);

        if ((broj % delenje_so) == 0)
        {
            lista.Add(brojac);
            delivi++;
        }

        brojac++;
    }

    for (int i = 0; i < lista.Count; i++)
    {
        //listBox1.SetSelected(lista[i], true);
        MessageBox.Show(lista[i].ToString());
    }
    listBox1.EndUpdate();

    label1.Text = delivi.ToString();
}

基本上,我有一个 ListBox、Button、TextBox 和 Label。我在 ListBox 中有一些项,并且我必须检查这些项(ints)是否可以被 TextBox 中的数字整除。然后选择所有可以在 ListBox 中被整除的项目,并输出可以被整除的数字总数到 Label 中。
我的代码中一切都正常,除了 ListBox 不会选择被除的项目。
我尝试在同一 foreach 循环中进行更新检查,但是我得到一个错误,说列表已被修改,不能继续。所以我制作了不同的循环,但出于某种原因它没有起作用。
2个回答

0
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace SOFAcrobatics
{
    public partial class Dividers : Form
    {
        public Dividers()
        {
            InitializeComponent();

            this.listBox1.SelectionMode = SelectionMode.MultiSimple;

            for (Int32 i = 1 ; i <= 30 ; i++)
            {
                this.listBox1.Items.Add(i);
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Int32 n = Int32.Parse(this.textBox1.Text);

            List<Int32> indexes = new List<Int32> ();

            Int32 counter = 0;

            for (Int32 i = 0 ; i < this.listBox1.Items.Count ; i++)
            {
                if ((((Int32)this.listBox1.Items[i]) % n) == 0)
                {
                    indexes.Add(i);
                }
            }

            for (Int32 i = 0 ; i < indexes.Count ; i++)
            {
                this.listBox1.SetSelected(indexes[i], true);
            }

            this.label1.Text = (indexes.Count + 1).ToString();
        }
    }
}

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接