如何为Page_LoadComplete和btnGenerateCode_Click重构代码并使用一个代码源

时间:2019-01-04 22:04:29

标签: c# asp.net

我在脚本的两个地方有相同的代码。此代码用于生成供学生输入的随机代码。我希望页面加载时默认情况下生成代码,并且如果教师不喜欢默认代码,则可以选择单击按钮以生成另一个代码。该页面现在可以使用,但是我只想获取一次代码。如何为页面加载完成和单击按钮调用相同的代码?

)
        protected void Page_LoadComplete(object sender, EventArgs e)
        {

            {
                //string alphabets = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
                //string small_alphabets = "abcdefghijklmnopqrstuvwxyz";
                string numbers = "1234567890";

                string characters = numbers;
                //if (rbType.SelectedItem.Value == "1")
                //{
                //characters += alphabets + small_alphabets + numbers;
                //characters += numbers;
                //}
                //int length = int.Parse(ddlLength.SelectedItem.Value);
                int length = 5;
                string otp = string.Empty;
                for (int i = 0; i < length; i++)
                {
                    string character = string.Empty;
                    do
                    {
                        //int index = new Random().Next(0, characters.Length);
                        int index = new Random().Next(0, 5);
                        character = characters.ToCharArray()[index].ToString();
                    } while (otp.IndexOf(character) != -1);
                    otp += character;
                }
                //lblOTP.Text = otp;
                txtAttendanceCode.Text = otp;
            }

        }



        protected void btnGenerateCode_Click(object sender, EventArgs e)
        {
            {
                //string alphabets = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
                //string small_alphabets = "abcdefghijklmnopqrstuvwxyz";
                string numbers = "1234567890";

                string characters = numbers;
                //if (rbType.SelectedItem.Value == "1")
                //{
                //characters += alphabets + small_alphabets + numbers;
                //characters += numbers;
                //}
                //int length = int.Parse(ddlLength.SelectedItem.Value);
                int length = 5;
                string otp = string.Empty;
                for (int i = 0; i < length; i++)
                {
                    string character = string.Empty;
                    do
                    {
                        //int index = new Random().Next(0, characters.Length);
                        int index = new Random().Next(0, 5);
                        character = characters.ToCharArray()[index].ToString();
                    } while (otp.IndexOf(character) != -1);
                    otp += character;
                }
                //lblOTP.Text = otp;
                txtAttendanceCode.Text = otp;
            }

        }

0 个答案:

没有答案