Page.IsPostBack是一个标志:当前请求是否第一次打开。 (4)每次页面Load的时候,根据需要把每次都要加载的代码放在IsPostBack中,只需要加载一次的代码放在if(!IsPostBack)中。 |
自己的小例子
写了个关于猜数字的
小程序
public partial class _Default : System.Web.UI.Page
{
//产生的随机数
int n;
//得到输入的数
int gettext;
//记录产生的随机数
int d;
//计入次数
static int i ;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
// 网页第一次加载时执行的操作
n = this.suijishu();
Label2.Text = n.ToString();
i = 0;
}
else
{
d = Convert.ToInt32(Label2.Text);
i++;
}
}
protected void Button1_Click1(object sender, EventArgs e)
{
try
{ //得到输入的数
gettext = Convert.ToInt32(TextBox1.Text);
//将判断结果赋给label
Label1.Text = this.panduan(gettext, d, i);
}
catch (Exception ex)
{
Label1.Text = "请输入数字!!!";
Console.WriteLine(ex.Message);
}
}
/// <summary>
/// 判断输入的数和随机数是否相等
/// </summary>
/// <param name="input">输入的数</param>
/// <param name="n">随机数</param>
/// <returns></returns>
public string panduan(int input, int n, int i)
{
//int i = 1;
//判断
if (input == n)
{
if (i == 0)
{
i = 1;
//Console.WriteLine("你太聪明了,太有才了");
return "你太聪明了,太有才了。你今天的运气很旺";
}
else if (i >= 2 && i <= 6)
{
i = 1;
//Console.WriteLine("这么迅速就猜出来,你很聪明");
return "这么迅速就猜出来,你很聪明,你今天的运气不错呀";
}
else if (i >= 7)
{
i = 1;
//Console.WriteLine("你太逊了,继续努力吧");
return "你太逊了,继续努力吧,你今天的运气不是很好,出门要小心呀";
}
//Response.Redirect(Request.Url.ToString());
}
else if (input > n)
{
//i++;
//Console.WriteLine("你猜的大了点");
return "你猜的大了点";
}
else if (input < n)
{
//i++;
//Console.WriteLine("您猜的小了点");
return "你猜的小了点";
}
return "";
}
/// <summary>
/// 产生随机数
/// </summary>
/// <returns></returns>
public int suijishu()
{
//new 一个随机数生成器
Random random = new Random();
//生成随机数,在10--289
int n = random.Next(0, 100);
return n;
}
protected void Button2_Click(object sender, EventArgs e)
{
Response.Redirect(Request.Url.ToString());
}
}