-1

I have a checklistbox and I want to randomly check a set number of the items in the textbox (CheckAmount.Text) - i.e. if the user enter 60%(0.60), I want 60% of the items in the checked listbox to be checked. Is this possible or even close?

int CA = Convert.ToInt32(CheckAmount.Text);
for (int i = 0; i <= CA; i++)
{

}
johnny 5
  • 19,893
  • 50
  • 121
  • 195
Linda
  • 7
  • 2
  • 2
    Possible duplicate of [How do I generate a random int number in C#?](https://stackoverflow.com/questions/2706500/how-do-i-generate-a-random-int-number-in-c) – David Zemens May 07 '18 at 21:43
  • https://stackoverflow.com/questions/273313/randomize-a-listt – battlmonstr May 07 '18 at 21:43
  • *exactly* will depend on things like the number of check boxes and whether modulus division allows for that sort of precision, e.g., if you have 11 checkboxes, you can check 6, or 7, but not 6.6. So you'll need to adjust your algorithm accordingly. – David Zemens May 07 '18 at 21:46

2 Answers2

0

I can get close, but what you are saying is to:

Check blah amount of CheckBoxes in CheckBoxList foo

Code:

//The CheckBoxList name is boxes
int CA = Convert.ToInt32(CheckAmount.Text);
Random rng = new Random();
int x = 0;
for (int y = CA; y != 0; y--)
foreach (CheckBox i in boxes.Controls)
{
     x = rng.Next(1, boxes.Length + 1); //have to add 1 or it will never pick the last box
     if(boxes[boxes.Controls.IndexOf(i)] == x - 1)
     {
          i.Checked = true;
          y--;
     }
     else
     {
          continue;
     }
}

What this does is it looks through all of the checkboxes, and randomly selects blah checkboxes from boxes and checks them. blah is CA in your code.

Hope it helps!

Techcraft7

Techcraft7
  • 129
  • 2
  • 12
  • Thank you. That worked!! But it does not check the items it only highlights them and each time it only selects one item of the list – Linda May 07 '18 at 22:51
0

If you want to check exactly 60% of the rows (or the closest that rounding errors will let you get), you should sort the rows randomly then take the first 60% of them.

For example:

var r = new Random();
var checkboxes = this.Controls.OfType<CheckBox>();
float totalBoxes = checkboxes.Count();
var targetCount = (int)(totalBoxes * 0.60F);

var targetItems = checkboxes
    .OrderBy( c => r.Next() )  //Sort randomly
    .TakeWhile( (c,i) => i <= targetCount );  //take the first 60%
foreach (var c in targetItems) c.Checked = true;
John Wu
  • 50,556
  • 8
  • 44
  • 80
  • Thank you - Im a bit confused with some of your code - could you annotate what i edit with my textboxes/checkboxes names please. I'm particularly not sure with the c and i – Linda May 08 '18 at 13:23