问题描述
我的ReservationID就像这个R00001但是当自动生成ReservationID时,值0不能保留在变量中。如何解决?
My ReservationID like this R00001 but when auto generate the ReservationID, the value 0 cannot keep in the variable. How to solve it ?
public void GenerateReservationID()
{
string sql = "SELECT * FROM Reservation";
string cs = @"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True";
string s = "";
SqlConnection con = new SqlConnection(cs);
SqlCommand cmd = new SqlCommand(sql, con);
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
s = Convert.ToString(dr["ReservationID"]);
}
string sub1 = s.Substring(0,1);
string sub2 = Convert.ToString(Convert.ToInt16(s.Substring(1)) + 1);
dr.Close();
con.Close();
lblRservationID.Text = sub1 + sub2;
}
[edit]已添加代码块 - OriginalGriff [/ edit]
[edit]Code block added - OriginalGriff[/edit]
推荐答案
SELECT MAX(ReservationID) FROM Reservation
将仅返回当前最高的数字,这是我怀疑你的感兴趣。
2)当你将一个字符串转换为一个整数时,你不会丢失零 - 但是将一个整数转换回来的常规方法字符串不会插入前导零 - 这就是你得到的效果。对于一个整数,00000001与1相同,因为前导零完全不相关。
尝试使用ToString格式来指定前导零,或者String.Format:
Will return only the current highest number, which is what I suspect you are interested in.
2) When you convert a string to an integer, you don't "lose" zeros - but the normal method to convert an integer back to a string does not insert leading zeros - so that is the effect you get. To an integer, 00000001 is the same as 1 because leading zeros are completely irrelevant.
Try using ToString with a format to specify the leading zeros instead, or String.Format:
string sub1 = s.Substring(0,1);
int reserveNp = Convert.ToInt32(s.Substring(1)) + 1;
lblReservationID.Text = string.Format("{0}{1:00000}", sub1, reserveNo);
3)虽然还有另一个问题:由于你使用SQL,很有可能在多用户环境中使用它,你在这里使用的想法是行不通的:如果两个用户同时去预订号码,那就有一个,很有可能他们都会得到相同的价值。
你在哪里创建这个预订ID,为什么不从那里保留价值?
3) There is another problem though: Since you are using SQL there is a good chance that this will be used in a multi user environment, where the idea you are using here will not work: if two users go for a reservation number at the same time, there is a very, very good chance that they will both get the same value.
Where are you creating this reservation ID, and why aren't you keeping the value from there?
这篇关于我在进行计算时无法保留该值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!