How to insert row in typed dataset

  • Thread starter Thread starter Benson
  • Start date Start date
B

Benson

I create a typed dataset by drag'n'drop in VS2005 (VB). I can use FillBy or
GetDataBy methods to retrieve the record. The code is as follows:

dataTable = tableAdapter.GetDataByCode(KeyFieldValue)
MtrUnitBindingSource.DataSource = dataTable
'user edits the record
'press ok button to save
MtrUnitBindingSource.EndEdit()
tableAdapter.Update(dataTable)
==> it works perfectly in find/edit/update mode.
Question:
1. I find difficulty in New/Insert mode. How to add a new row and do the
insert to the database?
2. If in the view mode (only user views the record), how to set datatable to
readonly?

Benson
VB2005
 
The best technique I've seen is to set your dataset PKs to negative seed and
increment (-1). I then use that value as a decision point as to whether to
create a new row or update the existing.

Obviously you have to AddNew on your bindingsource in order to add a new row
to the table. You do that before you populate the new row. Then just as you
EndEdit and Update, you do the same for your new rows (I actually do both
within the same method, then branch out depending upon which function I'm
performing). You must also call ResetCurrentItem on the bindingsource. This
is all shown well in the recent ADO.Net 2.0 books on the market (see the
ones by Vaughn, Malik, or Sceppa).

BindingSource.ResetCurrentItem()
eBindingSource.EndEdit()
 
To add a new row to a strongly typed dataset:

Dim ds As New NorthwindDataSet()
Dim tblCustomers As NorthwindDataSet.CustomersDataTable _
= ds.Customers
Dim rowCustomer As NorthwindDataSet.CustomersRow
rowCustomer.CustomerID = "NEWCO"
rowCustomer.CompanyName = "New Company"
tblCustomers.AddCustomersRow(rowCustomer)

'another way
tblCustomers.AddCustomersRow("NEWC2", "Another Co")

To remove update capability, you can change this on the
BindingSource:

MtrUnitBindingSource.AllowEdit = False
MtrUnitBindingSource.AllowNew = False
MtrUnitBindingSource.AllowRemove = False

To reset the add/change/delete ability back to whatever is
supported by the underlying data source:

MtrUnitBindingSource.ResetAllowNew
MtrUnitBindingSource.AllowEdit = True
MtrUnitBindingSource.AllowRemove = True

HTH,
Robin S.
 
I agree about setting the autoincrement settings to -1. But
if he's using a strongly typed dataset, calling Update on the table
adapter should automatically check the rowstate and insert the new
ones if the rowstate is Added.

I don't understand the use of ResetCurrentItem on the binding source.
I haven't found a need to use that. Can you explain that a bit?

I agree about the ADO.net books. I use Sceppa's book a lot.

Robin S.
-------------------------------------------------
 
Benson,

Try to have a look to the after MS Access method (although it is now in it
to), to use the Unique Identifier, in .Net called Global Unique Identifier
(GUID).

Cor
 
Back
Top