Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

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.

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.

Try:

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

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-"

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top