Expiring Today—Celebrate National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

How to place random numbers in labels?

Posted on 2008-10-17
10
Medium Priority
?
758 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 6
  • 4
10 Comments
 
LVL 86

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 86

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
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
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 86

Accepted Solution

by:
Mike Tomlinson earned 200 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
 
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 86

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 86

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 86

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

On Demand Webinar: Networking for the Cloud Era

Ready to improve network connectivity? Watch this webinar to learn how SD-WANs and a one-click instant connect tool can boost provisions, deployment, and management of your cloud connection.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

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…
Calculating holidays and working days is a function that is often needed yet it is not one found within the Framework. This article presents one approach to building a working-day calculator for use in .NET.
Sometimes it takes a new vantage point, apart from our everyday security practices, to truly see our Active Directory (AD) vulnerabilities. We get used to implementing the same techniques and checking the same areas for a breach. This pattern can re…
In response to a need for security and privacy, and to continue fostering an environment members can turn to for support, solutions, and education, Experts Exchange has created anonymous question capabilities. This new feature is available to our Pr…
Suggested Courses

718 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