Click here to Skip to main content
15,885,365 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
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
Posted
Updated 15-Feb-12 23:36pm
v3

C#
a = dr[0] == DBNull.Value ? 0 : Convert.ToInt32(dr[0]) +1;
 
Share this answer
 
Comments
Member 8614787 16-Feb-12 5:47am    
Thanks for reply but i got only for o values not 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:
C#
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!
 
Share this answer
 
Comments
Member 8614787 16-Feb-12 5:46am    
Thanks for your reply, but i need incerament the values in my table is makeid field here automatically increse the values in one by one (ex:1,2,3..)
OriginalGriff 16-Feb-12 6:05am    
You can't do that until you write your row into the DB - and then if it is an autoincrement field the value will be assigned by the DB, not you anyway - so the value you are displaying in your text box may have no bearing on the value the row gets when it is written.
Dear Friend,

Try this :-

a = dr[0] == DBNUll.Value ? 0 : dr.GetInt32(0) +1;


I hope this will work.
 
Share this answer
 
Comments
Member 8614787 16-Feb-12 6:09am    
hi i got the answer in this code i replace 0 is 1[ a = dr[0] == DBNUll.Value ? 1 : dr.GetInt32(0) +1;] after it's increament from 1,2.. work fine thanks for reply thank you
Varun Sareen 16-Feb-12 11:40am    
Dear Friend,

Then Please accept this as your answer or rate it :)

Thanks

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900