Generate random numbers till Button click (UWP) - c#

I have a textblock and a button.
I want the textblock to be filled with a random number when I click the button and it should change the random number every 5 seconds. When I click the button a second time it should stop at the last random number.
How do I make this? This is what I tried:
bool thisStatus = false;
private void btn_click(object sender, RoutedEventArgs e)
{
if (thisStatus == false)
{
thisStatus = true;
}
else thisStatus = false;
random();
}
private void random()
{
while (thisStatus)
{
Random random = new Random();
int RandomNumber = random.Next(0, 100);
txtBlck.Text = RandomNumber.ToString();
Task.Delay(5000);
}
}

bool thisStatus = false;
private async void btn_click(object sender, RoutedEventArgs e)
{
thisStatus = !thisStatus // mke the toggling simple.
await random();
}
private async Task random()
{
while (thisStatus)
{
Random random = new Random();
int RandomNumber = random.Next(0, 100);
txtBlck.Text = RandomNumber.ToString();
await Task.Delay(5000);
}
}
you need to await the task delay method because awaiting makes sure it completes before moving on.

You can use the dispatcher Timer
dispatcherTimer = new System.Windows.Threading.DispatcherTimer();
dispatcherTimer.Tick += new EventHandler(dispatcherTimer_Tick);
dispatcherTimer.Interval = new TimeSpan(0,0,5);
int RandomNumber;
Random random = new Random();
private void btn_click(object sender, RoutedEventArgs e)
{
if (thisStatus == false)
{
thisStatus = true;
dispatcherTimer.Start();
}
else {
thisStatus = false;
dispatcherTimer.Stop();
}
}
private void dispatcherTimer_Tick(object sender, EventArgs e)
{
RandomNumber = random.Next(0, 100);
}

Related

How to remove items in listbox that was randomly selected using timer

private void button1_Click(object sender, EventArgs e)
{
timer1.Start();
timer2.Start();
}
private void timer1_Tick(object sender, EventArgs e)
{
int a = int.Parse(label3.Text)
+ 1;
label3.Text = a.ToString();
if (label3.Text == "10")
{
listBox1.Items.Add(label1.Text);
label3.Text = "0";
}
}
private void timer2_Tick(object sender, EventArgs e)
{
Random rnd = new Random();
int num = rnd.Next(1, listBox2.Items.Count);
label1.Text = num.ToString();
if (label3.Text == "10")
{
listBox1.Items.Add(label1.Text);
listBox2.Items.Remove(label1.Text); //this line of code isnt working. It doesnt delete anything.
}
}
What i wanted to happen is my label1 will shuffle all the items(1-10) in my listbox2 using timer1 then if the timer reach 10 seconds the listbox1 will add label1 last number as its item and listbox2 will remove it. It's working fine but it doesnt remove what's in the listbox2
You can use:
int i = listBox2.Items
.Cast<ListBoxItem>()
.ToList()
.FindIndex(x=>x==label1.Text);
listBox2.RemoveAt(i);
UPDATE:
Random rnd = new Random();
private void timer2_Tick(object sender, EventArgs e)
{
int num = rnd.Next(1, listBox2.Items.Count);
label1.Text = num.ToString();
if (label3.Text == "10")
{
listBox1.Items.Add(label1.Text);
listBox2.Items.Remove(label1.Text); //this line of code isnt working. It doesnt delete anything.
}
}

I need my random values to look like they are rolling C#

I have five dice labels and I have a method Roll() that sets their
text value. At the moment when the roll method happens it just makes the numbers appear, but I would like them to look like they are rolling.
Here is what I have
//Roll() simulates the rolling of this die.
public void Roll()
{
if (Active) {
faceValue = random.Next(1, 7);
label.Text = faceValue.ToString();
}
}
Roll() is called from another class like this:
for (int i = 0; i < dice.Length; i++){
dice[i].Roll();
}
My Question is:
How can I let it looks like they are rolling through a set of numbers then stop on a number ?
Try this
public async void Roll()
{
if (Active)
{
for (int i=0;i<20;i++) //Number of rolls before showing final
{
await Task.Delay(100);
label.Text = random.Next(1, 7).ToString();
}
}
}
I tested a Little and this Looks good done in WPF with a DispatcherTimer:
DispatcherTimer timer = new DispatcherTimer();
private void Button_Click(object sender, RoutedEventArgs e)
{
timer.Tick += Roll;
timer.Interval = new TimeSpan(1);
Random r = new Random();
timer.Start();
}
Random r = new Random();
public void Roll(object sender, EventArgs e)
{
increment++;
if (increment >= 250)
{
timer.Stop();
increment = 0;
}
DiceLabel.Content = r.Next(1, 7).ToString();
timer.Interval = new TimeSpan(increment*3000);
}
If you want it faster or longer you can play with the value from:
timer.Interval = new TimeSpan(increment*3000);
here to set the time between the new number is shown.
And for the time to Dice is rolling, you can play with:
if (increment >= 250)
Hope that helps, have fun.

Problems of while(true) in C# "VS2012" {WinForm}

" int ans = 2;
private void Form1_Load(object sender, EventArgs e)
{
for (int i = 0; i <21; i++)
{
ans = 2;
label1.Text += i.ToString();
while (true)
{
if (ans == 1)
{
break;
}
}
}
}
private void button1_Click(object sender, EventArgs e)
{
ans = 1;
} "
this is a simple app
I want to print a number & then wait to the button to be clicked to break the while loop
but when I run the application , the form doesn't show .
"T think that the problem is the while (true)".
what to do?
Use a timer. Start the timer when the form loads. Each time it ticks, increment the number and display it. On button click, you just need to stop the timer.
private Timer _myTimer;
private int number = 0;
private void Form1_Load(object sender, EventArgs e)
{
_myTimer = new Timer();
_myTimer.Interval = 1; // 1 millisecond
_myTimer.Tick += new EventHandler(MyTimer_Tick);
_myTimer.Start();
}
// increments the number at timer tick
private void MyTimer_Tick(object sender, EventArgs e)
{
number ++;
// TODO: update UI here
}
// Stops the timer
private void button1_Click(object sender, EventArgs e)
{
_myTimer.Stop();
}
It's best to not use a loop here. Since this loop won't end you won't ever leave Form_Load and it won't display the form. If you were trying to do some task when the user clicks a button, why not move that logic to button1_Click?
The correct way to implement such a task as you describe would be as such:
private EventWaitHandle ewh = new EventWaitHandle(false, EventResetMode.AutoReset);
private void Form1_Load(object sender, EventArgs e)
{
Task.Factory.StartNew(() =>
{
for (int i = 0; i < 26; i++)
{
ewh.WaitOne();
Action updateLable = () => label1.Text = "" + i;
label1.BeginInvoke(updateLable);
}
});
}
private void button1_Click(object sender, EventArgs e)
{
ewh.Set();
}
As you can see I've replaced your busy wait (while(true)) with a .Net wait handle.
One of the answers describes a timer that acts every millisecond - that is a busy wait of sorts.
This is what async/await is for. Mark your Load() event with "async", then "await" a Task that continues when a ManualResetEvent is triggered in the Button click handler:
private System.Threading.ManualResetEvent mre = new System.Threading.ManualResetEvent(false);
private async void Form1_Load(object sender, EventArgs e)
{
for (int i = 0; i < 21; i++)
{
label1.Text = i.ToString();
mre.Reset();
await Task.Factory.StartNew(() => { mre.WaitOne(); });
}
button1.Enabled = false;
label1.Text = "Done!";
}
private void button1_Click(object sender, EventArgs e)
{
mre.Set();
}

How to delay for loop cycles?

I have a for loop where I calculate the value of something and display it, for example
void Button_Click(object sender, RoutedEventArgs e)
{
InitializeComponent();
Random rand = new Random();
for (i = 0; i <= 30; i++)
{
rnd = rand.Next(1,10);
value += i + rnd;
display.Content = value;
}
}
The problem is, I want to see the value overwritten after each cycle, delayed by X seconds, how could I achieve that in WPF?
Use Task.Delay to execute some code after a period of time.
private async void Button_Click(object sender, RoutedEventArgs e)
{
InitializeComponent();
Random rand = new Random();
for (i = 0; i <= 30; i++)
{
rnd = rand.Next(1,10);
value += i + rnd;
display.Content = value;
await Task.Delay(Timespan.FromSeconds(1));
}
}

how to make row flash every 3 seconds

I dont know if I'm doing this correctly but I have a grid and I loop through the grid to see if the items matched. If they do I want to make the row flash every 3 seconds. Right now what I have in my code just pretty much highlight the row but no flashing. Can anyone help take a look?
public static void CheckRow(int item, DataGridViewRow row)
{
List<int> col = new List<int>();
//call to db and add to col
foreach (var item in col)
{
if (item == col.Item)
{
currentRow = row;
Timer t = new Timer();
t.Interval = 3000;
t.Tick += new System.EventHandler(Highlight);
t.Start();
}
}
}
private static void Highlight(object sender, EventArgs e)
{
currentRow.DefaultCellStyle.BackColor = Color.Brown;
}
Wouldn't you need to change the color again (to the original) to have a flashing effect?
You should use Threading. Look at the code :)
bool go = false; //for changing cell color
int count = 10; //to stop timer (blinking)
public blinkForm()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
timer1.Start();
Thread a = new Thread(blink);
a.Start();
}
private void Form1_Load(object sender, EventArgs e)
{
dataGridView1.AutoGenerateColumns = false;
if (dataGridView1.Columns.Count == 0)
{
//generate new columns for DataGridView
dataGridView1.Columns.Add("user", "User");
dataGridView1.Columns.Add("pcStatus", "PC Status");
dataGridView1.Columns.Add("service", "Servis");
//generate new rows for DataGridView
dataGridView1.Rows.Add("Ali", "PC007", "chrome.exe");
dataGridView1.Rows.Add("Vusal", "PC010", "photoshop.exe");
dataGridView1.Rows.Add("Rahim", "PC015", "chrome.exe");
}
}
private void blink(object o)
{
while (count > 0)
{
while (!go)
{
//change color for binking
dataGridView1.Rows[0].Cells["service"].Style.BackColor = Color.Tomato;
go = true;
//stop for 0.5 second
Thread.Sleep(500);
}
while (go)
{
//change color for binking
dataGridView1.Rows[0].Cells["service"].Style.BackColor = Color.LimeGreen;
go = false;
//stop for 0.5 second
Thread.Sleep(500);
}
}
}
private void timer1_Tick(object sender, EventArgs e)
{
count--;
if (count == 0)
{
//stop blinking after 10 second
timer1.Stop();
}
}
Perhaps this, no?
private static void Highlight(object sender, EventArgs e)
{
currentRow.DefaultCellStyle.BackColor = Color.Brown;
System.Threading.Thread.Sleep(2000);
currentRow.DefaultCellStyle.BackColor = Color.White;
}

Categories