How to use result of a function to show in a message box and set in a text box at the same time? Do I use a Public or Private function? [closed]

StackOverflow https://stackoverflow.com/questions/17626215

  •  03-06-2022
  •  | 
  •  

Question

I have a function in my form that generates a random string. I want to show the result of this function in both a message box and a text box at the same time. How to? Should my function be public or private?

Here is my function:

    public string GenerateRandomCode(int myLength)
    {
        string charPool = "ABCDEFGOPQRSTUVWXY1234567890ZabcdefghijklmHIJKLMNnopqrstuvwxyz";

        StringBuilder rs = new StringBuilder();

        Random random = new Random();
        for (int i = 0; i < myLength; i++)
        {
            rs.Append(charPool[(int)(random.NextDouble() * charPool.Length)]);
        }

        return rs.ToString();
    }
Était-ce utile?

La solution

From what I understood, you want the text of a textbox to show the result of GenerateRandomCode and show that value in a MessageBox, too. You can do that like so:

int length = 10;
string msg;



private void button1_Click(object sender, EventArgs e)
{
    msg = GenerateRandomCode(length);
    textBox1.Text = msg;
    MessageBox.Show(msg);

}

Random random = new Random();

public string GenerateRandomCode(int length)
{
        string charPool = "ABCDEFGOPQRSTUVWXY1234567890ZabcdefghijklmHIJKLMNnopqrstuvwxyz";
        StringBuilder rs = new StringBuilder();
        /*Random random = new Random();*/

        for (int i = 0; i < length; i++)
        {
            rs.Append(charPool[(int)(random.NextDouble() * charPool.Length)]);
        }
        return rs.ToString();
 }

Autres conseils

As I understood it, you want to show it in a message box and text box. To show in MessageBox, you will invoke the method and pass the returned value to MessageBox, like this:

string Result = GenerateRandomCode(6);
MessageBox(Result);

To display it in a TextBox you can simply create it on your form(I don't know what type of form you are using) and assign Result to it:

TextBox textResult = new TextBox();
textResult.Text = Result;

Private methods can only be called by the class which owns the method. They are used without creating the object of the class. And Yes (!) you can do it all with a Private method as well.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top