QQ:285679784 欢迎加入博主CSDN资源QQ群799473954(附加信息:CSDN博客)一起学习 !
前端aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="CreateRandom.aspx.cs" Inherits="AspNetWebSocket.CreateRandom" ValidateRequest="false" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<p>所用字符:<asp:CheckBox ID="CheckBox1" runat="server" Text="A-Z" Checked="true" /> <asp:CheckBox ID="CheckBox2" runat="server" Text="a-z" Checked="true" /> <asp:CheckBox ID="CheckBox3" runat="server" Text="0-9" Checked="true" /> <asp:CheckBox ID="CheckBox4" runat="server" Text="!@#$%^&*" Checked="false" /></p>
<p>密码长度:<asp:DropDownList ID="DropDownList1" runat="server"></asp:DropDownList></p>
<p>生成结果:<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox></p>
<p><asp:Button ID="Button1" runat="server" Text="生成密码" OnClick="Button1_Click" /></p>
</div>
</form>
</body>
</html>
后端aspx.sc
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace AspNetWebSocket
{
public partial class CreateRandom : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
for (int i = 0; i < 99; i++)
{
DropDownList1.Items.Add((i + 1).ToString());
}
DropDownList1.SelectedIndex = 15;
}
}
protected void Button1_Click(object sender, EventArgs e)
{
if (!CheckBox1.Checked && !CheckBox2.Checked && !CheckBox3.Checked && !CheckBox4.Checked)
{
Response.Write("<font style=\"color: red;\">错误:请选择“所用字符”。</font>");
return;
}
//自定义组合字符
string strAll = "";
if (CheckBox1.Checked)
strAll += "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
if (CheckBox2.Checked)
strAll += "abcdefghijklmnopqrstuvwxyz";
if (CheckBox3.Checked)
strAll += "0123456789";
if (CheckBox4.Checked)
strAll += "!@#$%^&*";
//定义一个结果
string result = "";
//实例化Random对象
Random random = new Random();
//使用for循环得到6为字符
for (int i = 0; i < (DropDownList1.SelectedIndex + 1); i++)
{
//返回一个小于当前自定义组合字符串长度的int类型的随机数
int rd = random.Next(strAll.Length);
//随机从指定的位置开始获取一个字符
string oneChar = strAll.Substring(rd, 1);
result += oneChar;
}
TextBox1.Text = result;
Response.Write("<font style=\"color: blue;\">结果文字长度:" + result.Length + "</font>");
}
}
}