Cross Vander
Cross Vander

Reputation: 2157

Auto generated ID from DB in ASP.NET

I have a primary key for my table employee. I named it "IDS". The IDS data is like : K-00001, K-00002, etc. what I want to ask is, how to made this IDS auto generate in ASP.NET, not using trigger or function in SQL?

I have done my code like this:

            DBRabbit _db = new DBRabbit();
            Employee k = new Employee();
            var row = (from r in _db.Employees
                       orderby r.IDS descending
                       select r).FirstOrDefault();
            var n = row.IDS.PadLeft(5, '0');    
            IDSText.Text = n.ToString();

And I'm stuck while think how to adding the 'n' to + 1.. because when I write like this:

var n = row.IDS.PadLeft(5, '0')+1; 

(last record is K-00010)
the result is K-000101 how to make it K-00011 without changing DB or using SQL server script/queries?

Upvotes: 1

Views: 2399

Answers (5)

Amogh Rai
Amogh Rai

Reputation: 159

are you using javascript for the above? if so try using

var n = (number(row.ids.substring(2))+1).toString().PadLeft(5,'0')

the substirng function is to remove the "k-"

Upvotes: 0

Tony Hopkinson
Tony Hopkinson

Reputation: 20320

Just have an auto inc integer somewhere (DB in preference) and then build your no doubt very meaningful representation with

String.Concat("K-",KeyValue.ToString().PadLeft(5,'0');

Your way is lot of messing about with an almost guaranteed chance for Murphy to play with your head. Just don't do what you are doing.

Upvotes: 1

Kaf
Kaf

Reputation: 33819

You better make your IDS column auto incremented as James said. Also if you need to have another column for K-00010, K-00011,... I would suggest you to use a computed column with the following formula

'K-' + cast( right([IDS]+(100000),(5)) as varchar(5))

EDIT: Formula corrected.

Upvotes: 5

James Johnson
James Johnson

Reputation: 46047

Make the column auto-incrementing. As a rule of thumb, you should never increment primary keys manually -- that's just begging for issues. The right sequence of events would compromise that logic.

Upvotes: 2

MikeTWebb
MikeTWebb

Reputation: 9279

Try:

var n = (Convert.ToInt32(row.IDS) + 1).ToString().PadLeft(5, '0');

Upvotes: 0

Related Questions