get random item from listBox c# - c#

i have a listBox and i want everytime show random item from my list.
var random = new Random();
int index = random.Next(listBox1.Items.Count);
Console.Writeline(listBox1.Items[index].toString());

var random = new Random();
int index = random.Next(0, listBox1.Items.Count);
Console.Writeline(listBox1.Items[index].toString());

var random=new Random();
int index=random.Next(0,listBox1.Items.Count);
Basically random.Next(min,max) require min and max values so that random number is generated between the given range.
You should provide range also .
Console.Writeline(listBox1.Items[index].toString());

I just use your code #ilyas it's working fine, stick with it, just use
MessageBox.Show(listBox1.Items[index].ToString());
instead of
Console.Writeline(listBox1.Items[index].toString());
i assume you are creating WinForm Application

Your code seems to be ok. But if you are using it in a tight loop, it would give you always the same number. Maybe this is your problem?
Every time you do new Random() it is initialized using the clock.
This means that in a tight loop you get the same value lots of times. You should keep a single Random instance and keep using Next on the same instance.
//Define your random class with a static field
public static class RandomAccessor {
// Static field for your Random to create one instance only
private static readonly Random random = new Random();
// Object to lock sync on
private static readonly object syncLock = new object();
// Method to generate random number
public static int RandomNumber(int max)
{
lock(syncLock) {
// returns a random non-negative number less that max
return random.Next(max);
}
}
}
Then use it in your code like this:
int index = RandomAccessor.RandomNumber(listBox1.Items.Count);
Console.Writeline(listBox1.Items[index].toString());
Ask if you have any questions.

Here is a basic example how it will work.
using System;
using System.Windows.Forms;
namespace SimpleFormsApplication
{
public partial class Form1 : Form
{
private readonly Random _random = new Random();
public Form1()
{
InitializeComponent();
}
private void button_random_Click(object sender, EventArgs e)
{
int randomIndex = _random.Next(listBox1.Items.Count);
var randomItem = listBox1.Items[randomIndex];
MessageBox.Show($"Random item at index {randomIndex} is {randomItem}");
}
}
}
Please also have a look in here https://msdn.microsoft.com/en-us/library/system.random(v=vs.100).aspx and exermine the examples there.

Related

c# Which is the better way to give random number to function

Which is better and is there a difference in the random results ?
void Func1(Random rand)
{
var num=rand.Next();
}
void Func2(ref Random rand)
{
var num=rand.Next();
}
They are functionally equivalent. You don't update the rand reference in the function so passing it by ref does nothing.
Rule of thumb: don't use ref unless you absolutely have to and understand what it does.
1) Never use ref if you don't need it explicitely.
2) Usually you shouldn't need to pass Random through methods. If you have to, probably you are doing something wrong in your code.
Why? Because to be sure of a true randomness, it's better to always use the same Random instance instead of creating many of them.
That's why you should always declare one and use it around, like in this example:
class Program
{
static void Main(string[] args)
{
RandomNumbersPrinter randomNumbersPrinter = new RandomNumbersPrinter();
int randomInteger = randomNumbersPrinter.GetRandomInteger();
Console.WriteLine(randomInteger);
}
}
public class RandomNumbersPrinter
{
private static readonly Random _random = new Random();
public int GetRandomInteger()
{
return _random.Next();
}
}
Since Random is a reference type, the only difference is that the reference to the instance get copied when calling Func1.
In Func2, you are passing the actual existing reference to the Random itself to the method.
Please consult the docs for more information about this.
The bottom line is that you shouldn't use the ref keyword here unless you intend to assign rand to a new Random object in the method.

How do I make a quick program which goes through a list in a C# Windows Form Application?

I was experimenting with lists in C#'s console application, specifically a randomized int list which had its number order randomized. In this experiment I wanted to go through the randomized values from the list when I pressed enter and when it had shown all the randomized values it would stop. And it worked just as I intended: http://i.imgur.com/bNOYrZp.png[^]
Random r = new Random();
int tempValue;
List<int> number = new List<int>();
number.Add(1);
number.Add(2);
number.Add(3);
number.Add(4);
number.Add(5);
number.Add(6);
number.Add(7);
number.Add(8);
number.Add(9);
number.Add(10);
for (int i = 0; i < 10; i++)
{
tempValue = r.Next(0, number.Count);
Console.WriteLine(number[tempValue]);
number.RemoveAt(tempValue);
Console.ReadLine();
}
Now how do I do a similar thing in C#'s Windows Form Application? Instead of pressing enter to go through the list, I press a button to go through the list, and the order of the values are displayed on a label every time I press this button.
I used a similar code, but it did not work as intended. Instead of going through the randomized values it kept making a new order of values which it kept doing every time I clicked the button. What I want it to do is to go through the randomized values and after it has showed all the 10 randomized values, without duplicates, it stops.
private void button1_Click(object sender, EventArgs e)
{
List<int> number = new List<int>();
Random r = new Random();
int tempValue;
number.Add(1);
number.Add(2);
number.Add(3);
number.Add(4);
number.Add(5);
number.Add(6);
number.Add(7);
number.Add(8);
number.Add(9);
number.Add(10);
for (int i = 0; i < 10; i++)
{
tempValue = r.Next(0, number.Count);
label1.Text = number[tempValue].ToString();
number.Remove(number[tempValue]);
}
}
Since you put the list creation and for loop in the click event, its working "as-coded" (obviously not what you intended).
Remember, the entire click handler runs every time you press the button. So you need to initialize the list elsewhere and then just iterate through it on click. Something like:
private Random rng = new Random();
private List<int> numbers = new List<int>();
private void Form_Loaded(...) //Set to Form's Loaded event
{
number.Add(1);
number.Add(2);
number.Add(3);
number.Add(4);
number.Add(5);
number.Add(6);
number.Add(7);
number.Add(8);
number.Add(9);
number.Add(10);
}
private void button1_click(...)
{
tempValue = rng.Next(0, number.Count);
label1.Text = number[tempValue].ToString();
number.Remove(number[tempValue]);
}
Note that this code will have a few issues once the list runs out, there is no way to re-initialize the list, etc. I leave those as an exercise to you.
Also note that I created one instance of Random and stored it at the class level. In general, you want to use one instance per class to avoid seeding issues (though recreating it in the button click would have technically worked, since you probably can't click the button fast enough).

2 instances of class using random number

So I am trying to learn some C#, currently on a short course on An Introduction to Programming. I have a question in my text book which is giving me pretty much simular results to this post Same random numbers from instantiated class
I have tried to follow the solution but get the same results every time, the task is to Roll two dice and display their numbers using 2 instances of a class. But like the post above the "dice" role the same number. If I call the same instance of the class twice and out put the values to separate labels I get completely different values like i want. here is the class:
namespace CH10_Ex10._5
{
public class ThrowDice
{
public ThrowDice()
{
}
private Random newRandom = new Random();
private int x;
public void Throw()
{
x = newRandom.Next(1, 7);
}
public int value
{
get
{
return x;
}
}
}
}
and here is my main form:
namespace CH10_Ex10._5
{
public partial class Form1 : Form
{
ThrowDice Die1;
ThrowDice Die2;
public Form1()
{
InitializeComponent();
Die1 = new ThrowDice();
Die2 = new ThrowDice();
}
private void button1_Click(object sender, EventArgs e)
{
Die1.Throw();
dieOneLabel.Text = Convert.ToString(Die1.value);
Die2.Throw();
dieTwoLabel.Text = Convert.ToString(Die2.value);
}
}
}
I have tried to find an answer with out opening a new post so i am sorry if this have been answered before. I am very green at this.
My understanding is that if i declare objects with new, then i am creating separate instances of the class and therefore when i call those objects they should run independently/separately, but use the same rules which are specified in my class. I have tried to debug and as i step through the code i see the 2 separate calls to the class and what it looks like is the call 1 generates a random number eg 6 and call 2 seems to generate 6 as well.
thanks in advance
The problem is that the random instance will be initialized with the current time since you're using the default constructor. Since that happens on two instances very quick they get the same seed here:
public Form1()
{
InitializeComponent();
Die1 = new ThrowDice();
Die2 = new ThrowDice();
}
You could make it static:
private static Random newRandom = new Random();
Random constructor:
The default seed value is derived from the system clock and has finite
resolution. As a result, different Random objects that are created in
close succession by a call to the default constructor will have
identical default seed values and, therefore, will produce identical
sets of random numbers.
However, Random is not thread safe. So you should have a look at this answer.
This is also really worth reading: C# in Depth: Random numbers which suggests to use ThreadLocal<T> which is new in .NET 4 instead of static with lock.
You can fix this using same random instance in both instances.For example you can add a constructor like this:
private Random newRandom;
public ThrowDice(Random rnd)
{
newRandom = rnd;
x = newRandom.Next(1, 7);
}
Then:
Random rnd = new Random;
public Form1()
{
InitializeComponent();
Die1 = new ThrowDice(rnd);
Die2 = new ThrowDice(rnd);
}
What i usually use :
private Random newRandom = new Random(Guid.NewGuid().GetHashCode());

ObservableCollection updating from one method but not another

I have a method that updates my observableCollection
public void UpdateBeat()
{
SequenceCollection = new ObservableCollection<Sequence>();
Random random = new Random();
int randomNumber = random.Next(0, 100);
SequenceCollection.Add(new Sequence(1, 2));
}
I have 2 different methods fired from events - the view updates from 1 of the methods but not the other.
//Does not work
private void BsOnUpdateStep(object sender, EventArgs eventArgs)
{
Console.WriteLine("BS Update");
UpdateBeat();
}
//Works
void total_AudioAvailable(object sender, AsioAudioAvailableEventArgs e)
{
Console.WriteLine("ASIO Written");
UpdateBeat();
}
I have no idea what the difference could be here. The only thing I can tell is that the 1st method fires more often than the 2nd. I cannot get the 2nd to work at all.
I suppose your calls to UpdateBeat are from different threads but ObservableCollection is not thread safe, that is why -probably- you have such strange results.
You should look for an concurrent ObservableCollection.
One such implementation can be found here: http://www.codeproject.com/Tips/414407/Thread-Safe-Improvement-for-ObservableCollection
Try this:
private SequenceCollection = new ObservableCollection<Sequence>();
Random random = new Random();
public void UpdateBeat()
{
int randomNumber = random.Next(0, 100);
SequenceCollection.Add(new Sequence(1, 2));
}
I put the Random instantiation outside of the method too as you should only instantiate this once to get a proper stream of random numbers.

Windows form application - C# Random numer guessing game

I need a little help with a Random Number Guessing Game in visual studio. I got the brunt of the code down but I am having troubles with the Random number generator and getting the random number to port into the click events. As always, I don't really need code but some guidance and/or explanations as to what I am doing wrong and if there is a more effecient way to do things in the beginner phases of learning. Below is my code, the comments are the parts where I am having troubles. Thanks for any help as the help I've recieved to date as been phenominal.
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 LAB6B
{
public partial class game : Form
{
public game()
{
InitializeComponent();
//Generate Random number between 1 and 100
//Not sure if there is a better way?
Random rand1 = new Random();
int num1 = rand1.Next(1,50);
int num2 = rand1.Next(1,50);
int answer = num1 + num2;
}
private void evaluate_Click(object sender, EventArgs e)
{
int count = 0;
int choice = Convert.ToInt32(guess);
if (guess.Text != string.Empty)
{
// set counter to keep track of how many tries
// should this be done by a loop or will it count without a loop?
count++;
//compare user input against random number
//Can’t import the random number for comparision
if (choice < answer)
{
Evaluate.Visible = false;
lblMessage.Visible = true;
lblMessage.Text = "Too Low!";
Clear.Visible = true;
BackColor = Color.LightSeaGreen;
}
else if (choice > answer)
{
Evaluate.Visible = false;
lblMessage.Visible = true;
lblMessage.Text = "Too High!";
Clear.Visible = true;
BackColor = Color.SlateBlue;
}
else
{
//Display correct message along with how many times it took to get it
MessageBox.Show(" Eso es CORRECTO! It took you {0} tries. ", count);
}
}
}
private void Clear_Click(object sender, EventArgs e)
{
guess.Text = "";
Evaluate.Visible = true;
lblMessage.Visible = false;
Clear.Visible = false;
BackColor = Color.PowderBlue;
}
}
}
As the rand1 and answer variables are defined within the constructor, you can only access them in the constructor. Defining answer on the class level will solve most of the problems, as you will be able to access it both from the constructor and the click handlers, like this:
private int answer;
private int count;
public game()
{
InitializeComponent();
//Generate Random number between 1 and 100
Random random= new Random();
// no need for num1 and num2, it's just as random
answer = random.Next(1,101);
}
I think you have an issue of scope. The "answer" variable is declared inside your constructor, so it will not be visible to the code inside evaluate_Click(…).
Looks like you need to declare answer as a class variable. When you declare a variable in a constructor, it's still local to that method and not available to other methods.
I do not really know what you want answered, but an obvious error is that you must define your count variable as a member variable in order to keep track of the number of tries. As it is now, the count will always be initialized as zero each time the user presses the button.
First of, you need to declare your variable answer in the page level so it can be used by other page level functions.
Do it like this
public partial class game : Form
{
int answer;
public game()
{
}
}
in your counter you can use a static counter or a page level variable also such as the variable answer
just reset the counter when the user have guessed correctly

Categories