Random number in Entry

Borisoprit 371 Reputation points
2021-02-22T13:56:26.397+00:00

Found this to create a random number .

https://learn.microsoft.com/en-us/dotnet/api/system.random?view=net-5.0

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));  
Console.WriteLine();  

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()  
        {  
            base.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

70711-to-string-error.png

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

Accepted answer
  1. John Hardman 161 Reputation points
    2021-02-22T15:47:25.017+00:00

    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));
    

    to

    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,791 Reputation points
    2021-02-22T15:33:13.22+00:00

    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
    2021-02-22T19:22:37.997+00:00

    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