自动递增编号 [英] Auto increment number
本文介绍了自动递增编号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想知道如何在asp.net/C#中制作自动递增ID,我需要在文本框中显示此处,我的代码是
i want to know that how to make auto-increment id in asp.net/C# i need display in textbox here my code is
con.Open();
int a=0;
SqlCommand com = new SqlCommand("select max(makeid) from make",con);
SqlDataReader dr = com.ExecuteReader();
if(dr.Read())
{
a = Convert .ToInt32 (dr[0].ToString ())+1;(here show the error)
}
txtmakeid.Text = Convert.ToString(a);
con.Close();
但是我得到的错误是"输入字符串的格式不正确."如何解决这个问题
But i got error is "Input string was not in a correct format." how to solve this one
推荐答案
a = dr[0] == DBNull.Value ? 0 : Convert.ToInt32(dr[0]) +1;
即使您解决了它,也是这样做的危险方法.
如果不同的用户同时调用相同的代码会怎样?还是在执行此操作之后,但在将记录添加到数据库之前呢?答案:你们两个都以相同的号码结尾.
首先,放弃转换,并通过标量将其返回:
Even if you do solve it, that is a dangerous way to do it.
What happens if a different user calls that same code at the same time? Or even after you do this, but before you add your record to the database? Answer: you both end up with the same number.
First off: ditch the conversions, and return it via a scalar:
con.Open();
int a=0;
SqlCommand com = new SqlCommand("select max(makeid) from make",con);
int a = com.ExecuteScalar();
txtmakeid.Text = Convert.ToString(a);
con.Close();
哪个可以解决您的当前问题.
但这不会解决重复的值!
Which would cure your immediate problem.
But it won''t solve the duplicate values!
亲爱的朋友,
试试这个:-
Dear Friend,
Try this :-
a = dr[0] == DBNUll.Value ? 0 : dr.GetInt32(0) +1;
我希望这可以.
I hope this will work.
这篇关于自动递增编号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文