Click here to Skip to main content
15,922,584 members
Please Sign up or sign in to vote.
4.00/5 (2 votes)
See more:
How to make an item's value in comboBox have a specific range?

For example:

We will produce 5 values, the values come from random(1,15). And each value must have different min 2 point from other.
Example of output (with comment):
3
8 --> 8 is higher 2 point from 6
6
12
13 --> 13 is higher 1 point from 12, we must prevent this one

Here my code:

Public Class Form2
    Private Sub Form2_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Dim random As New Random(), i As Integer = 1
        Do While i < 5
            Dim newItem As Int32 = random.Next(1, 15)
            If Not cmbRnd.Items.Contains(newItem) Then
                cmbRnd.Items.Add(newItem)
                i = i + 1
            End If
        Loop
    End Sub
End Class



Sorry my english bad. i'm an indonesian :)
Posted
Updated 14-May-11 20:06pm
v2

All you have to do is increase the range of tests:
If Not cmbRnd.Items.Contains(newItem) Then
Becomes
If Not (cmbRnd.Items.Contains(newItem - 1) OrElse cmbRnd.Items.Contains(newItem) OrElse cmbRnd.Items.Contains(newItem + 1) Then
 
Share this answer
 
Comments
Abdi tombang 15-May-11 3:31am    
Thanks a lot Griff :D
I'm vote 5 for you :)
OriginalGriff 15-May-11 3:34am    
You're welcome
You miss the condition part.

Try something like this.

C#
int i = 0;
var random = new Random();
var randomList = new List<int>();

while (i < 5) {
   int x = random.Next(1, 15);
   if (!randomList.Contains(x) || !randomList.Contains((x + 1)) || !randomList.Contains((x - 1))) {
      randomList.Add(i);
      ++i;
   }
}

randomList.ForEach(r => cmbRnd.Items.Add(r.ToString()));



VB
VB
Dim i As Integer = 0
Dim random = New Random()
Dim randomList = New List(Of Integer)()

While i < 5
    Dim x As Integer = random.[Next](1, 15)

    If Not randomList.Contains((x + 1)) OrElse Not randomList.Contains((x - 1)) OrElse Not randomList.Contains(x) Then
        randomList.Add(i)
        i += 1
    End If
End While

randomList.ForEach(Function(r) cmbRnd.Items.Add(r.ToString()))


Hope it helps for your assignment.

<edit>
The important part is the condition
List should not contain (random or random+1 or random-1)
 
Share this answer
 
v3
Comments
Abdi tombang 15-May-11 3:30am    
Thanks a lot Pong D. Panda :D
I'm vote 5 for you :)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900