Solved

How to place random numbers in labels?

Posted on 2008-10-17
10
735 Views
Last Modified: 2012-05-05
Hello all

Using C#. I've placed on a Form two labels.

The code suppose to generate two random numbers and place each number in the labels (first number to first label, second number to second label)

How do I do that in the code?

Code examples will greatly appreciated !

thank you
0
Comment
Question by:liorb
  • 6
  • 4
10 Comments
 
LVL 85

Expert Comment

by:Mike Tomlinson
ID: 22744292
At its simplest:

    Random r = new Random();
    label1.Text = r.Next().ToString();
    label2.Text = r.Next().ToString();
0
 
LVL 1

Author Comment

by:liorb
ID: 22746028
Good solution but it's not exactly what I need.
I forgot to mention that the random number generation has to be in one method and the number placement must be in another method.
It's important that all the numbers generation and math calculations are in other methods then the one which will obtain them in the labels.
0
 
LVL 85

Expert Comment

by:Mike Tomlinson
ID: 22746907
Ok...that's pretty vague and smells ~slightly~ like homework.  =\

Please give more details on exactly how this should work.  It could be done in sooooooo many ways....

Do you need a CLASS to hold the two numbers?  ...and you have methods to tell it to generate the two numbers and Properties to retrieve the values?

Any more constraints?  Like the random numbers must be between X and Y?  Can the two random numbers be the same?  Are you going to call this repeatedly?  If so, is a combination that was generated previously considered valid?

I could go on and on....
0
 
LVL 1

Author Comment

by:liorb
ID: 22747426
No homework my school days are long over :)
I'm trying to learn C# on my own!

As I mentioned before in my program I have two labels which contain random number.
The process that I'm aim for works like that:
a) Random number generated  numbers between 3-19
b) I do a simple calculation with that number - (x-10)/2
c) The outcome of that calculation inserted to the first label
d) The same process (a-c) goes for the second label (and the third and fourth ....)
e) The numbers that are now represented in the labels will be used for further use

It will be nice if all the calculations and number generations will be in another class that is accessible all time.

I hope that clears things.

Thanks for the much appreciated help
:)
0
 
LVL 85

Accepted Solution

by:
Mike Tomlinson earned 50 total points
ID: 22749994
Does this help get you started?

The form simply has a Button with two Labels (button1, label1, label2):
using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Text;

using System.Windows.Forms;
 

namespace WindowsApplication1

{

    public partial class Form1 : Form

    {

        public Form1()

        {

            InitializeComponent();

        }
 

        private RandomPair rp = new RandomPair(3, 19);
 

        private void button1_Click(object sender, EventArgs e)

        {

            rp.GenerateRandomPair();

            this.label1.Text = rp.Number1.ToString() + " --> " + rp.CalculatedValue1.ToString();

            this.label2.Text = rp.Number2.ToString() + " --> " + rp.CalculatedValue2.ToString();

        }
 

        private class RandomPair

        {

            private Random R = new Random();

            private Int32 _num1 = 0;

            private Int32 _num2 = 0;

            private Int32 _min = 0;

            private Int32 _max = 100;
 

            public RandomPair(Int32 min, Int32 max)

            {

                this.Min = min;

                this.Max = max;

                this.GenerateRandomPair();

            }
 

            public Int32 Number1

            {

                get

                {

                    return this._num1;

                }          

            }
 

            public Int32 Number2

            {

                get

                {

                    return this._num2;

                }

            }
 

            public Int32 Min

            {

                get

                {

                    return this._min;

                }

                set

                {

                    this._min = value;

                }

            }

            

            public Int32 Max

            {

                get

                {

                    return this._max;

                }

                set

                {

                    this._max = value;

                }

            }
 

            public void GenerateRandomPair()

            {

                this._num1 = this.R.Next(this.Min, this.Max + 1);

                this._num2 = this.R.Next(this.Min, this.Max + 1);

            }
 

            public decimal CalculatedValue1

            {

                get

                {

                    return ((decimal)this.Number1 - (decimal)10) / (decimal)2;

                }

            }
 

            public decimal CalculatedValue2

            {

                get

                {

                    return ((decimal)this.Number2 - (decimal)10) / (decimal)2;

                }

            }
 

        }
 

    }

}

Open in new window

RandomPair.jpg
0
Top 6 Sources for Identifying Threat Actor TTPs

Understanding your enemy is essential. These six sources will help you identify the most popular threat actor tactics, techniques, and procedures (TTPs).

 
LVL 1

Author Comment

by:liorb
ID: 22751442
First of all thank for your hard work
I appreciate it a lot :)

I now stating, by your example, to understand how the get & set are implemented to use.

What is the roll of "this" command in the code?
0
 
LVL 85

Expert Comment

by:Mike Tomlinson
ID: 22752530
"this" refers to the current instance of an object.  It is CONTEXTUAL as what it refers to is based on the what its current SCOPE is.

In the button1_Click() method, "this" is referring to the FORM itself and the actual instance that is being displayed on the screen:

        private void button1_Click(object sender, EventArgs e)
        {
            rp.GenerateRandomPair();
            this.label1.Text = rp.Number1.ToString() + " --> " + rp.CalculatedValue1.ToString();
            this.label2.Text = rp.Number2.ToString() + " --> " + rp.CalculatedValue2.ToString();
        }

In the RandomPair() class:

        private class RandomPair
        {
             // ...
        }

When "this" appears inside that class it is referring to the current instance of RandomPair.  You can create many instances of a class.  The "this" keyword allows us to refer to the instance we are currently using.  In contrast, if we were OUTSIDE the RandomPair class and we wanted to refer to an instance we would need a variable such as:

    private RandomPair rp = new RandomPair(3, 19);

In this case, "rp" is referring to an instance of RandomPair.

0
 
LVL 85

Expert Comment

by:Mike Tomlinson
ID: 22752543
With respect to the "get" and "set" implementations...

Note that the "Number1" and "Number2" properties are READ-ONLY because they only have the "get" implementations.  From OUTSIDE the class you can read these properties but not change them.

The "Min" and "Max" properties are read/write because they have both "get" and "set".  You can change their values from outside the class.  We could put additional code inside the "set" methods to prevent the user from setting a min/max value that is smaller/larger than the other value.  We wouldn't want a "min" of 10 and a "max" of 3 right?  I didn't put in an error checking with respect to that.

0
 
LVL 1

Author Comment

by:liorb
ID: 22755937
Mike you are the best

This is more then I asked for.
From you I've learned so much - thanks a lot :)

two more Question:
In the code you gave the value 100 to the _max number
"          private Int32 _min = 0;
            private Int32 _max = 100;   "
Why  this number and not another (why not 20 or any other number)?

Why using 'int32' and not just 'int'?

I do have more questions but I afraid to be nuisance

0
 
LVL 85

Expert Comment

by:Mike Tomlinson
ID: 22758186
The 0 and 100 are just arbitrary values I picked.  =)

It doesn't matter much anyway since I made the constructor accept the desired min/max values:

    public RandomPair(Int32 min, Int32 max)

So the 0 and 100 just get replaced when the class is instantiated...

Some great discussion on 'int' vs 'int32':
http://stackoverflow.com/questions/62503/c-int-or-int32-should-i-care
Essentially they are the same.
0

Featured Post

Highfive + Dolby Voice = No More Audio Complaints!

Poor audio quality is one of the top reasons people don’t use video conferencing. Get the crispest, clearest audio powered by Dolby Voice in every meeting. Highfive and Dolby Voice deliver the best video conferencing and audio experience for every meeting and every room.

Join & Write a Comment

Introduction                                                 Was the var keyword really only brought out to shorten your syntax? Or have the VB language guys got their way in C#? What type of variable is it? All will be revealed.   Also called…
Article by: Ivo
C# And Nullable Types Since 2.0 C# has Nullable(T) Generic Structure. The idea behind is to allow value type objects to have null values just like reference types have. This concerns scenarios where not all data sources have values (like a databa…
In this tutorial you'll learn about bandwidth monitoring with flows and packet sniffing with our network monitoring solution PRTG Network Monitor (https://www.paessler.com/prtg). If you're interested in additional methods for monitoring bandwidt…
Polish reports in Access so they look terrific. Take yourself to another level. Equations, Back Color, Alternate Back Color. Write easy VBA Code. Tighten space to use less pages. Launch report from a menu, considering criteria only when it is filled…

759 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

20 Experts available now in Live!

Get 1:1 Help Now