Random number in Entry

Borisoprit 371 Reputation points

Found this to create a random number .


var rand = new Random();  
Console.WriteLine("Five random integers between 0 and 100:");  
for (int ctr = 0; ctr <= 4; ctr++)  
    Console.Write("{0,8:N0}", rand.Next(101));  

This is what i try to do but cannot get it to work in Entry with the name Randomnr.

Cannot convert type to String

 protected async override void OnAppearing()  
            var rand = new Random();  
            for (int ctr = 0; ctr <= 4; ctr++)  
                Randomnr.Text = ("{0,8:N0}", rand.Next(101));  

Randomnr.Text = ("{0,8:N0}", rand.Next(101).ToString);
Is also not working , then this


A Microsoft open-source app platform for building Android and iOS apps with .NET and C#.
5,313 questions
0 comments No comments
{count} votes

Accepted answer
  1. John Hardman 161 Reputation points

    You haven't said what format you want the text to be in, but to get it at least compiling change

    Randomnr.Text = ("{0,8:N0}", rand.Next(101));


    Randomnr.Text = $"{rand.Next(101),00000000}";

    That will give you the random number as a string with leading zeros to pad to 8 characters in length.

    If you simply want the random number with no adornment, I'd go for ToString instead of string interpolation, and instead do the following:

    Randomnr.Text = rand.Next.ToString(); // you can add a format provider etc as an argument to ToString if you want

    You can also remove the following line (I assume you only want one random number in your Entry)

    for (int ctr = 0; ctr <= 4; ctr++)
    1 person found this answer helpful.
    0 comments No comments

2 additional answers

Sort by: Most helpful
  1. Nasreen Akter 10,766 Reputation points

    Hi @Borisoprit ,

    Would you please try the following. Thanks!

     Randomnr.Text += rand.Next(101).ToString()+ " ";  


    If the above response is helpful, please Accept as answer and Up-vote it. Thanks!

  2. Borisoprit 371 Reputation points

    Thanks for the reply nasreen-akter and JohnHardman .

    This is what i use now , and is working good i think

    var rand = new Random();
    Randomnr.Text = $"{rand.Next(101),00000000}";
    0 comments No comments