private void button2_Click(object sender, EventArgs e)
{
Process.Start("http://google.com");
}
for example, then when clicked again it has a chance of opening like yahoo or even google again. tried
private void button2_Click(object sender, EventArgs e)
{
Process.Start("http://google.com");
Process.Start("http://yahoo.com");
Process.Start("http://stackoverflow.com");
}
but that opens up all 3 sites at the same time in my default browser I want it to open 1 out of those 3 sites randomly each time the button is clicked.
Use the Random
class and limit the random numbers within an interval:
Java sample as original post was not marked with language, for C# - remove final
and use System.Random
to select value:
private void button2_Click(object sender, EventArgs e)
{
final String[] urls = {
"http://google.com",
"http://yahoo.com",
"http://stackoverflow.com"
};
final int pick = (int)(Math.random() * urls.length);
Process.Start(urls[pick]);
}
You can create a string array to hold the site addresses, like so:
string[] sites = {
"http://google.com",
"http://yahoo.com",
"http://stackoverflow.com" };
And then use the Random
class to select one of those sites on your button click:
private void button2_Click(object sender, EventArgs e)
{
Random random = new Random();
Process.Start(sites[random.Next(sites.Length)]);
}
The Next
method of the random class will return a value less than the specified number, so no chance of an array out of bounds exception
Random number generator (should be a library for it in c#.
Add in a couple variables with your links, maybe store them in an array.
Then run that line you have with the array at the index that was randomly generated.
Random rnd = new Random();
int website = rnd.Next(0, numOfWebsites);
switch(website)
{
case 0:
{
Process.Start("http://google.com");
break;
}
case 1:
{
Process.Start("http://yahoo.com");
break;
}
}
You can use a switch case statement for readability with a random number generator. I apologize if i made any errors as i don't use C# much. A if else statement would also work for a situation like this.
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.