自动填充数据表列数据表

2023-09-06 09:45:37 作者:阳光暖暖的。

你如何填写一个DataTable(比方说,唯一标识符)的特定的列上建立一排,这样你总是可以假定列都将有一个有用的价值?

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()

但它需要FormattingEnabled,所以我怀疑这是不是真的工作(财产的依然得心应手,谢天谢地)。我不希望有洒

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();

语句随处可见我创建一个新的行 - 我preFER做一次,然后高枕无忧知道,我创建一个新的行每一次,它会具有唯一标识符

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.

推荐答案

您应该抓住的上的数据表,这是您创建一个使用NEWROW()方法的一个新的DataRow每次发射TableNewRow 事件。在事件处理程序,你可以prepopulate所有你需要有默认值的列。

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.

需要注意的是缺省值不从数据库流过,所以不依赖于具有 NEWID的缺省值的唯一标识符列() - 这并不意味着在你的数据表中新行会Guid.NewGuid()作为其默认值。这就是TableNewRow是。

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.