[英]generate a unique ID in c#
I tried to generate a unique ID starting from 1 but the number stays the same.. I'm trying to use session variable so it can go like 1,2,3,4... 我试图从1开始生成一个唯一的ID,但数字保持不变。我正在尝试使用会话变量,所以它可以像1,2,3,4 ...
Main page: 主页:
protected void calculateButton_Click(object sender, EventArgs e)
{
int bookingID = 0;
bookingID += 1;
bookingIDTextBox.Text = bookingID.ToString();
}
protected void confirmButton_Click(object sender, EventArgs e)
{
Session["confirmBooking"] = "confirm";
Session["bookingID"] = bookingIDTextBox.Text;
Response.Redirect("MainBookingForm.aspx");
}
Second page: 第二页:
protected void newBookingButton_Click(object sender, EventArgs e)
{
string bookingRef = (string)(Session["bookingID"]);
Session["bookingRef"] = bookingRef;
Response.Redirect("BookingForm.aspx");
}
You are declaring the variable each time you press the button, so it will always be 1 每次按下按钮都会声明变量,因此它始终为1
Declare the variable outside the method 在方法外声明变量
int bookingID = 0;
protected void calculateButton_Click(object sender, EventArgs e)
{
bookingID += 1; // You can also use bookingID++
bookingIDTextBox.Text = bookingID.ToString();
}
EDIT note that it will be reset when you restart the application, you might want to store it somewhere (application settings / database etc) EDIT请注意,重启应用程序时会重置它,您可能希望将其存储在某处(应用程序设置/数据库等)
you can use the Application object - it is part of the HttpContext and is directly accessible on any page. 您可以使用Application对象 - 它是HttpContext的一部分,可以在任何页面上直接访问。
If you don't want to use it, you may want to write a Globals class (or whatever name you like) that holds static members. 如果您不想使用它,您可能希望编写一个包含静态成员的Globals类(或您喜欢的任何名称)。
public class Globals
{
public static int Counter { get; set;}
}
// accessed from other classes:
Globals.Counter++;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.