使用c#在文本框中自动增加数字 [英] Auto Increment number in textbox using c#
问题描述
我正在开发Windows应用程序并希望自动生成交易号。
我写了以下代码: -
I am working on windows application and want to auto generate transaction number.
I wrote the following code:-
private void Form1_Load(object sender, EventArgs e)
{
int a;
string cnstr = //Your connection string;
SqlConnection con = new SqlConnection(cnstr);
con.Open();
string query = "Select Max(Trans_No) from Auto_Number";
SqlCommand cmd = new SqlCommand(query,con);
SqlDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
string val = dr[0].ToString();
if (val == "")
{
textBox1.Text = "1";
}
else
{
a = Convert.ToInt32(dr[0].ToString());
a = a + 1;
textBox1.Text = a.ToString();
}
}
}
Sql表查询是
Sql Table Query is
Create Table Auto_Number
(
Trans_No varchar(10)
primary key (Trans_No)
)
我想自动递增转码并在文本框中显示。上面的代码将生成数字并显示在文本框中,生成的数字将保存在按钮单击上。它工作正常,直到转码数为9,当生成转号10时,当我点击保存时它被保存,但在sql表中我看到转号10保存在第二个位置或行。然后没有生成数字。
我在调试模式下运行项目,查询返回的值是9.
所以我解除了上面提到的相同查询SQL服务器中的代码,即
I want to auto increment the trans number and show it in textbox. the above code will generate the number and display in textbox and the number generated is saved on button click. It works fine till the trans number is 9 and when the trans number 10 is generated and when I click on save it is saved, but in sql table I saw trans number 10 is saved at 2nd position or Row. and then the number is not generated.
I run the project in debug mode and the value returned from query was 9.
So I fired the same query as mentioned in above code in SQL server i.e.
Select Max(Trans_No) from Auto_Number
中选择Max(Trans_No),答案是相同的,即9.
请帮忙!!!
先谢谢!!!
and the answer was same i.e 9.
Any help please !!!
Thanks in Advance !!!
推荐答案
我将查询更改为: -
I changed the query to:-
select Max(Cast(Trans_No as Int)) from Auto_Number
select top 1 Trans_No from Auto_Number order by Trans_No Desc
我在<$ c时想到的东西$ c>数据类型Trans_No
是Varchar
然后9之后
它插入重复值
表示每当我保存Value然后而不是(10 + 1)= 11
保存10
而不是11
然后我只是将Trans_No数据类型更改为Int
然后它是工作正常的家伙
所以你必须尝试更改数据类型希望这件事能在我的工作中发挥作用:)
What I Figured out whenDatatype
ofTrans_No
isVarchar
then after9
it is insertingduplicate value
means everytime when i''m saving the Value then instead of(10+1)=11
it is saving10
instead of11
then i just Changed theTrans_No Datatype To Int
then it is Working Fine Dude
So U Must try to Change The Datatype Hope This Thing will Work as Mine is Working :)
这篇关于使用c#在文本框中自动增加数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!