How to set default values for data bound controls for addition in VB.NET

feldoh picture feldoh · Jun 18, 2012 · Viewed 7.7k times · Source

I have a vb.net 2010 form with 22 data bound controls from two tables held in a dataset which is navigated by a bindingnavigator. This successfully adds deletes and updates. However what I need is when adding a new record I need some of the fields to be pre filled out. More specifically I have points balance fields etc which could be any value but will normally be 0 on a new customer so I want to initialise them to 0 when adding new records.

I located an AddingNew event on my datasource but this is called before the new item is added and thus all my initialisation is lost.

any help on this would be appreciated. kind regards Feldoh

Answer

LarsTech picture LarsTech · Jun 18, 2012

Since you are using DataTables, you can manually set the DefaultValue property of the DataColumn:

Dim dt As New DataTable
Dim dc As New DataColumn("test", GetType(String))
dc.DefaultValue = "hello"
dt.Columns.Add(dc)
dt.Rows.Add()
Debug.WriteLine(dt.Rows(0)("test").ToString)

Result: hello