I am writing a code for a school exercise and I have the following code:
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();
}
Basically, I have a ListBox
, Button
, TextBox
and a Label
. I have some items in ListBox
and I have to check if those items ( ints
) can be divided by the number in TextBox
. Then select all the items that can be divided in the ListBox
and output the total amount of numbers that can be divided in the Label
.
Everything works in my code, except the fact that ListBox
will not select the items that are divided.
I tried updating in the same foreach
loop that I do the checking, but I get an error that list has been modified and can't continue. So I made different loop, but nothing happens with it for some reason.
In order to have multiple items selected, you will need to set the listbox's SelectionMode
property to MultiSimple
or MultiExtended
:
The SelectionMode property enables you to determine how many items in the ListBox a user can select at one time …
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();
}
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.