Wednesday, November 23, 2011

Resetting a table's identity in SQL Server

The following syntax is what's needed if at any time you need to reset the auto-identity (INT) of any table.

DBCC CHECKIDENT([tablename(string)], [command], [numbertoreseedto(int)])

So, for example, if I wanted to reset the current identity value for my Customer table to 39, I would write the following:

DBCC CHECKIDENT('Customer', RESEED, 39)

Note that the table name is in quotes. Also, it's important to note that the number you use for your reseed will increment by one for the next new entry into the table. Generally speaking you will be reseeding to the last known identity value in your table. So, in my example above, if the last row entry reads 39 as its ID column, then I will reseed to 39, meaning the next row I add will have an ID value of 40. I can reseed to 40 if I choose (actually you can in theory reseed to anything equal to or beyond the maximum ID value in the table currently), but it would mean that you'd end up with a 'gap' in your column IDs; so they might read: 39, 41, 42... and so on, with 40 being missing because of the way the RESEED occurred. So, assuming you're aiming for consecutive numbers (which most of us are when it comes to IDs for table rows) then always reseed to the last known identity value.

Tuesday, November 01, 2011

ASPX data-bound values and Javascript combined - tips and tricks

There are ways at combining ASPX data bound portions of code neatly with Javascript and some of the syntax is not very memorable and can be tricky. To get a reference to a server control on the page via javascript, use the ClientID property, like so:
var grid = document.getElementById("<%= CurrApprovalsGrid.ClientID %>");
Alternatively, if you're using jQuery:
var grid = $find("<%= CurrApprovalsGrid.ClientID %>");
To pass bound values (inside 'Eval' methods) to a javascript function, the syntax is the following:
OnClientClick='<%# "if (!checkDocument(" + Eval("JobId") + "," + Eval("SubJobId") + ")) return false;" %>'
Make careful note of the extra speech marks - these must be included as is or the page will break.

To fire an ItemCommand on a server side control in a grid view - for example a LinkButton from javascript code, use the following syntax:
var masterTable = $find("<%= CurrApprovalsGrid.ClientID %>").get_masterTableView(); masterTable.fireCommand("ViewLatest", ""); // 'ViewLatest' is the name of the CommandName

Fixes to common .NET problems, as well as information on .NET features and solutions to common problems that are not language-specific.

Fixes to common .NET problems, as well as information on .NET features and solutions to common problems that are not language-specific.

Z