tags:

views:

451

answers:

4

How do you fill out a particular column of a DataTable (say, a uniqueidentifier) on creation of a row so that you can always assume that column is going to have a useful value?

I've got this column bound to a property on an object of mine with

NullValue = Guid.NewGuid()

but it requires FormattingEnabled and so I suspect that this isn't really working (property's still handy, thankfully). I don't want to have to sprinkle

row[UniqueID] = Guid.NewGuid();

statements everywhere I'm creating a new row - I'd prefer to do it once, then rest easy knowing that every time I create a new row, it'll have a uniqueidentifier.

A: 

The database should be the place where new row ID's are created. If you are using SQL Server, you can create a Primary Key column with a UniqueIndentifier specification, and each time you add a new record, the database will assign a Unique Identifier to it automatically.

Robert Harvey
That'd be nice, except I need to know what the primary key is because I need to use it and putting rows into the database triggers validation that the row isn't necessarily going to pass if I do it blindly. It's much easier for me to create my own uniqueidentifier.
Merus
+1  A: 

You should catch the TableNewRow event on the DataTable, which is fired every time you create a new DataRow using the NewRow() method. In the event handler you can prepopulate all the columns you need to have "default" values.

Note that default values don't flow through from the database, so don't rely on a uniqueidentifier column having a default value of newid() - it doesn't mean that new rows in your DataTable will get Guid.NewGuid() as their default values. That's what TableNewRow is for.

Matt Hamilton
Exactly what I'm after! Thank you.
Merus
A: 

You can use DataColumn.DefaultValue for the integers with seed and increment, but not with NewGuid(), because all the values will be the same.

Why not use Guid.NewGuid() at time of insertion, or instead of using DataTables use a List(Of SomeClass) where you can fine tune things like default values of properties in the class.

CRice
A: 

While I agree with Robert that the database is where defaults should be specified, it is entirely possible your using a DataTable for a different purpose, possibly AS a data store? Anyway, to my knowledge, there should be a TableNewRow event on your DataTable. Just handle that, and add your guid that way:

DataTable myTable = new DataTable(); myTable.TableNewRow = myTable_TableNewRow;

// ...

private void myTable_TableNewRow(object sender, DataTableNewRowEventArgs e) { e.Row[k] = Guid.NewGuid(); }

jrista