We use cookies to give you the best experience on our website. If you continue to browse, then you agree to our privacy policy and cookie policy. Image for the cookie policy date

AddNew to DataGrid and set two primarykeys

Hi Folks. How do I set values into two columns when I make an Addnew (the last row in grid) to the grid ? The underlying datatable has a primary key that is a combined key of two fields and dont allow Null values. So I must set the values in the AddNew 'mode'. One way I am trying is to fetch the CurrentChanged on a CurrencyManager. cm = Me.BindingContext(dsApproverReplacers.ApproverReplacers) AddHandler cm.CurrentChanged, AddressOf AddNewReplacersToGrid After that I have to look if the row is a AddNew row (How I dont know yet). I saw an exampel where you compare the datatable rowcount with the datagrid rows and if it differs the you are at the AddNew (not pretty). Another way could be to remove the null check on the datatable and set the keys afterwards... But there must be a simpler way that I dont see. Can anybody help me ?

1 Reply

JI jim February 2, 2003 10:43 PM UTC

There may be a better way, but here are two ways to do what you suggested: Set the "allow db null" property to true, and set it after the row is added. You can go after the "Table Row Changed" event on the data source. If the key field(s) are null, set them: AddHandler dtMaster.RowChanged, AddressOf HandleMasterTableRowChanged Protected Overrides Sub HandleMasterTableRowChanged(ByVal sender As Object, ByVal e As System.Data.DataRowChangeEventArgs) 'ID goes in as null, but be "saved" as numassign If e.Row("employee_id") Is DBNull.Value Then Dim rowKey As Int32 = GetNewKey() "employee_id"= rowKey End If End Sub ****** The other way is trap the the ListChanged event of the datasource. This is a really usefull event because it fires when the grid is sorted, or when you add or delete a row. AddHandler dtMaster.DefaultView.ListChanged, AddressOf HandleMasterViewListChange Protected Overrides Sub HandleMasterViewListChange(ByVal sender As Object, ByVal args As System.ComponentModel.ListChangedEventArgs) If args.ListChangedType = System.ComponentModel.ListChangedType.ItemAdded Then Dim dt As DataTable dt = DataManager.DataTable 'You get an Added when you move to the new row, and when you save it. 'Ignore the case of moving to the row... there's not row in the datatable yet! Dim dv As DataView dv = CType(sender, DataView) If dt.Rows.Count = args.NewIndex Then Dim oCurrent As Object oCurrent = m_bindingmanager.Current Dim drv As DataRowView = CType(oCurrent, DataRowView) Dim dr As DataRow = drv.Row If dr.RowState = System.Data.DataRowState.Added Then If dr("employee_id") Is DBNull.Value Then Dim rowKey As Int32 = GetNewKey() dr("employee_id") = rowKey End If End If End If End If End Sub

Loader.
Live Chat Icon For mobile
Up arrow icon