创建随机客户编号并将其显示在文本框中

时间:2013-01-16 18:24:23

标签: c# random

我完全坚持创建一个随机数。理想情况下,与客户编号的数字不同两倍。

然后我需要在我的tb_id(文本框)中显示它并将该行写入客户文件。

这里的任何帮助都会很棒。

private void button1_Click(object sender, EventArgs e)
{    
    **var rng = new Random();**
    // Here I need to write the random number (it's a customer number) to the tb_id text box. so I'm able to write it to their customer file afterwards.

    try
    {
        string fileName = string.Format(tb_surname.Text);

        if (tb_firstname.Text == "" || fileName == "" || tb_postcode.Text == "")
        {
            MessageBox.Show("Missing values from textboxes!");
        }
        else if (File.Exists(fileName + "Text"))
        {
            if (MessageBox.Show("Warning: There is already a file with the surname you enter already on the system. Contents will be replaced - do you want to continue?", "File Demo", MessageBoxButtons.YesNo, MessageBoxIcon.Question,
                 MessageBoxDefaultButton.Button1, MessageBoxOptions.DefaultDesktopOnly) == DialogResult.Yes)
            {
                //write lines of text to file
                StreamWriter outputStream = File.CreateText(fileName + ".Txt");
                outputStream.WriteLine(tb_firstname.Text);
                outputStream.WriteLine(tb_surname.Text);
                outputStream.WriteLine(tb_surname.Text);
                **outputStream.WriteLine(tb_id.Text);**
                outputStream.Close();
                MessageBox.Show("Text saved to file successfully!");
                this.Close();
            }
        }
    }
    // ...
}

第2部分

       // creating a random number here for the customer id
        Guid g = Guid.NewGuid();
        tb_id.Text = g.ToString();

将Guid编号写入文本文件。

        outputStream.WriteLine(tb_id.Text);

3 个答案:

答案 0 :(得分:7)

我不建议使用随机数,如果你想让它对用户来说是唯一的,那么很有可能让不同的用户拥有相同的号码。

guid可能是更好的主意

  Guid g = Guid.NewGuid();

答案 1 :(得分:1)

首先,如果你只是使用随机数识别用户,那么使用像COLD TOLD这样的GUID说。

唯一随机是完全不同的事情


但是为了理解如何使用随机数......

rng声明为Random

类型

要实际创建随机数,请输入类似

的内容
int randI =  ng.Next(0, 1000);

将为您提供0到1000之间的随机数。

您可以使用Intellisence查看随机数字的其他选项。

将该数字放在文本框中,而不是

textBox1.Text = randI.ToString();

答案 2 :(得分:1)

您可以使用Guid结构。 GUID是全局唯一标识符,它在.NET框架中提供

 this.iD = Guid.NewGuid().ToString();