StrataFrame Forum

Copy Current Record

http://forum.strataframe.net/Topic13603.aspx

By Bill Cunnien - 1/21/2008

I searched the forum in vain for an answer to this.  How do I copy the current record of  BO to a new record in the same BO, reset a couple of values, navigate to that new record and allow the user to alter any necessary fields before saving?  This seems very simple.

Thanks,
Bill

By Trent L. Taylor - 1/21/2008

Yeah, you can just create a shared (sorry static since you are C# Wink) method that copies the data out of the row.  This is probably something we could add to the Tools.Common class, but just haven't as of yet.

'-- Save off the current row
Dim copyRow As DataRow = MyBo.CurrentRow
MyBo.NewRow()

'-- Now update each of the columns within the new row.  You may want to test
'    on certain column names to be excluded, such as PK fields.
For each col as DataColumn In MyBo.CurrentDataTable.Columns
    MyBo.Items(col.ColumnName) = copyRow.Item(col.ColumnName)       
Next

I didn't run this to make sure that the copyRow didn't move (I just typed it in here) but it should be close enough to get you going.

By Bill Cunnien - 1/21/2008

I did something similar a couple of minutes ago.  I added a BO to the form and named it PartTempBO.  When the user clicks the button, I fill that BO with the FillByPrimaryIndex method from the index of the primary BO.  Then, I run the Add() method on the primary BO.  I manually set the properties of the new record to the properties of the temp record (except the differentiating field...partnum); however, after reading your reply, I think I will try the walk the collection route.  That would be easier...especially, since I know we will be modifying that data table's structure over the next several weeks.

Thanks a lot for your help!
Bill

By Bill Cunnien - 1/21/2008

There does not appear to be an items collection within the business object.  Here is my code:

DataRow mCurrentPart = partsBO1.CurrentRow;
partsBO1.Add();
foreach (DataColumn mCol in partsBO1.CurrentDataTable.Columns)
{
   
if (mCol.ColumnName!="partindex")
    {
        partsBO1.Items(mCol.ColumnName) = mCurrentPart.Items(mCol.ColumnName);
    }
}

The items (in red) do not exist (at least, not by intellisense; therefore, compiler won't like it either).  I cannot seem to find anything comparable in the BO.

Also, is there a way to tell if the column is a PK or not?

Oh, I am using Add() rather than NewRow() because I need the user to save the data after he is done updating the record.  The NewRow() adds the appropriate empty row, but leaves the state unchanged.  The Add() method does create a new row, but it also places the item into an editable state.  The beauty there is that all of the bound controls are refreshed, too.

Thanks!
Bill

By Paul Chase - 1/22/2008

Bill you can just drop the .items.

For example MyBO("ColumnName") = proposed value or you could do mybo.currentdatatable.items("columnname") = proposed value. the first example is probably better has it calls through SF logic thus events are raised etc.

To find the primary key you can check the primary key field property .

if mCol.ColumnName = mybo.primarykeyfield then

 it is the primary key

endif

However if you are using compound pk's then there is a primarykeyfields collection you would have to loop through the collection to check if it was a PK.

Hope that helps

Paul

By Bill Cunnien - 1/22/2008

Excellent Paul!  Thanks!!

I am wondering, though, why no property explicitly exists in the business object called "FieldName".  Over time I have forced myself not to use shortcuts like this one (e.g. myBO[myCol.ColumnName]).  I would rather do something like myBO.FieldName[myCol.ColumnName].  The code is a tad more readable.  The default property can change (doubt it will, but I have no control over that) so this would eliminate a lot of code fixups later down the road.

Maybe it is there and I just am not referencing it correctly.  Still learning.  Wink

Bill

By Bill Cunnien - 1/22/2008

Is it this?

myBO.CurrentDataTable.Columns[myCol.ColumnName]

The DataRow has a similar definition:

myDataRow.Table.Columns[myCol.ColumnName]

By Bill Cunnien - 1/22/2008

Ran into another issue while testing...null values.  These things just get everywhere...like a bad rash!  Even after I have the replace value option set on a specific column, the error thrown is a null value issue.  It is trying to copy a null and it doesn't like it.  Any words of wisdom on this one?
By Bill Cunnien - 1/22/2008

Here is the offending code:

private class Field_lentolerance_Descriptor : MicroFour.StrataFrame.Business.FieldPropertyDescriptor
{
   
public Field_lentolerance_Descriptor() : base("lentolerance") { }
   
private System.Type _PropertyType = typeof(System.String);
   
public override object GetValue(Object component)
    {
       
return ((PartsBO)component).lentolerance;
    }
   
public override void SetValue(Object component, object Value)
    {
        ((
PartsBO)component).lentolerance = (System.String)Value;    <----THIS IS THE OFFENDING LINE
    }
   
public override System.Type PropertyType
    {
       
get
       
{
           
return this._PropertyType;
        }
    }
   
public override System.Type ComponentType
    {
       
get
       
{
           
return _ComponentType;
        }
    }
}

Since this code is in the designer class, I assume there is a way to handle this via the Object Mapper.  I'm just not seeing it.

Bill

By StrataFrame Team - 1/23/2008

You cannot set a NULL value through the strong-typed property... and the .Item property (the indexer in C#, where you just use the []) uses those strong-typed properties.  In order to copy over the NULL values, you will need to bypass the strong-typed properties by using the .CurrentRow property like so:

In your foreach loop, change the:

partsBO1.Items(mCol.ColumnName) = mCurrentPart.Items(mCol.ColumnName);

to:

partsBO1.CurrentRow[mCol] = mCurrentPart.CurrentRow[mCol.ColumnName];

If you noticed, I used the column reference on the first and the column name on the second... that's because the fastest way to reference a column of a DataRow is by passing the column reference, but since the column belongs to the first BO and not the second, you have to use the name to reference the second one.  You could use the name on both, but then the DataRow would just use the name to find the column reference and then use it, so you might as well pass the column reference since you have it.

By Bill Cunnien - 1/23/2008

Ben Chase (01/23/2008)

partsBO1.CurrentRow[mCol] = mCurrentPart.CurrentRow[mCol.ColumnName];

Sorry...I am a bit confused.  A DataRow object doesn't have a CurrentRow property, does it?  I'll try using the CurrentRow of the BO to see if that makes a difference.

By StrataFrame Team - 1/24/2008

Woops, didn't look at the sample closely enough... didn't realize you were copying to a new record within the same business object... try this instead:

partsBO1.CurrentRow[mCol] = mCurrentPart[mCol];

By Bill Cunnien - 1/24/2008

Ben Chase (01/24/2008)
try this instead:

partsBO1.CurrentRow[mCol] = mCurrentPart[mCol];

I changed just the BO side per your earlier suggestion.  It seems to work just fine.  I do have the second half looking like this, though:

mCurrentPart[mCol.ColumnName]

I am assuming that ColumnName is the default property to DataColumn object.  So leaving it there or removing it won't matter, eh?

By Edhy Rijo - 3/16/2008

Trent L. Taylor (01/21/2008)
This is probably something we could add to the Tools.Common class, but just haven't as of yet.

Hi Trent,

I am looking for the same functionality here but in VB, was this added to SF?

By Trent L. Taylor - 3/17/2008

I guess I don't know what you are referring to.  You can view the previous post I had here that shows how to copy a record: http://forum.strataframe.net/FindPost13606.aspx .  This sample code is in VB.NET.  We haven't added a method to the tools class for this. 

If this isn't what you are looking for then you might elaborate on what functionality you are trying to implement.

By Edhy Rijo - 3/17/2008

Trent L. Taylor (03/17/2008)
I guess I don't know what you are referring to.  You can view the previous post I had here that shows how to copy a record: http://forum.strataframe.net/FindPost13606.aspx .  This sample code is in VB.NET.  We haven't added a method to the tools class for this. 

If this isn't what you are looking for then you might elaborate on what functionality you are trying to implement.

Hi Trent,

Yes I am referring to the following code:

'-- Save off the current row
Dim copyRow As DataRow = MyBo.CurrentRow
MyBo.NewRow()

'-- Now update each of the columns within the new row.  You may want to test
'    on certain column names to be excluded, such as PK fields.
For each col as DataColumn In MyBo.CurrentDataTable.Columns
    MyBo.Items(col.ColumnName) = copyRow.Item(col.ColumnName)       
Next

I just wanted to know if it was added to the framework so I could use it.  I have several address fields which could use this approach to be updated from an existing record.

By Trent L. Taylor - 3/17/2008

There is not a framework function to do this....you are really better off creating a shared method on a class somewhere that does this for you so you can "tweak" it to your needs.  When we started to add this method to the framework, we realized that there would have to be a LOT of overloads to try to accomodate this is a generic method.  It is still on our list, but not in the framework yet.  You can do this yourself very easily using the code supplied in the post.  I recommend created a sealed class to house all of your "basics" and then you could add a static (shared) method to that class to do this for you:

Public NotInheritable Class MyBasics
    '-- Seal the class
    Private Sub New()
    End Sub

   Public Shared Function CopyRecord(ByVal sourceRow As DataRow) As DataRow
      '-- Add the logic from the previous post here with your "tweaks"
   End Function
End Class

By Edhy Rijo - 3/17/2008

Thanks again, will follow your advice.
By Edhy Rijo - 9/5/2008

Here is my implementation of copying the current record into the same business object in a ListView control.

Private Sub tsbCopyAndAddRecord_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tsbCopyAndAddRecord.Click

     '-- If there is not item selected in the list, then

     '-- instruct the user to select a record first.

     If Me.lstItems.SelectedItems.Count = 0 Then

          Me.ShowMessageByKey("SelectRecordToCopy")

          Exit Sub    

     End If

     Try

          '-- Save off the current row

          Dim copyRow As DataRow = Me.BizItems1.CurrentRow

          If Me.BizItems1.NewRow() Then

               '-- Now update each of the columns within the new row.

               For Each col As DataColumn In Me.BizItems1.CurrentDataTable.Columns

                    '-- Skip the Primary Field, since the field is autoincremented or

                    '-- a generated GUID

                    If col.ColumnName = Me.BizItems1.PrimaryKeyField Then

                         Continue For

                    End If

                    '-- Do the actual copy of each field or column here.

                    Me.BizItems1.CurrentRow(col) = copyRow(col)

               Next

               '-- Show the ChildForm for the copied record.

               Me.EditChildRecord()

          End If

     Catch ex As Exception

     End Try

End Sub

In the above code I am using a method EditChildRecord() that I created from the source code of the listview, which I requested an enhancement to make this method public or shared here http://forum.strataframe.net/Topic19108-9-1.aspx for this kind of functionality.  I am not including my version here since I hope it will be made available to use in the framework.

By Juan Carlos Pazos - 2/15/2009

Hi Edhy

Thanks for your commentes. Can you post a sample of how to make the EditChildRecord?

Regards

By Edhy Rijo - 2/16/2009

Juan Carlos Pazos (02/15/2009)
Hi Edhy

Thanks for your commentes. Can you post a sample of how to make the EditChildRecord?

Regards

Juan Carlos, here ae the two mehods need for this functionality, I simply copied them from the source to the form where the ListView is being used and modified as needed.

''' <summary>

''' 09/08/2008 Edhy Rijo

''' Edits the currently selected child record

''' This method should be use temporarily until the internal one in the listview

''' is made available by SF Team

''' </summary>

''' <remarks></remarks>

Private Sub EditChildRecord()

     Dim bo As BusinessLayer = Me.lstItems.BusinessObject

     '-- If no business object is attached then there is nothing to do

     If bo Is Nothing Then Exit Sub

'-- See if a snapshot should be taken

If Me.lstItems.AutoSnapshotBusinessObject Then bo.SaveCurrentDataTableToSnapshot(Me.lstItems.AutoSnapshotKey)

'-- Ensure the the correct record is selected in case it had been moved by the developer

               bo.NavigateToPrimaryKey(Me.lstItems.SelectedItems(0).Tag)

               '-- Place the record in edit mode

               bo.Edit()

               '-- See if there is a child dialog

               If lstItems.ChildForm IsNot Nothing Then

                    '-- Raise the before child form executed event

                    ' OnBeforeChildFormExecuted(New ListViewBeforeChildExecuteEventArgs(ListViewChildFormAction.Edit))

                    '-- Call the child form and create the args

                    Dim args As New MicroFour.StrataFrame.UI.Windows.Forms.ListViewChildFormResultsEventArgs(MicroFour.StrataFrame.UI.ListViewChildFormAction.Edit, Me.lstItems.ChildForm.ShowDialog())

                    ''-- Raise the event

                    Me.lstItems_ChildFormResults(Me.lstItems, args)

                    '-- See if the list should be requeried

                    If args.Requery Then

                         '-- Save off the primary key value

                         Dim reselect As Boolean = True

                         Dim pk As Object = Nothing

                         Try

                              pk = bo.CurrentRow(bo.PrimaryKeyField)

                         Catch ex As Exception

                              reselect = False

                         End Try

                         '-- Requery the list

                         Me.lstItems.Requery()

                         '-- Attempt to select the item

                         If reselect Then SelectIndexByPrimaryKey(pk)

                    End If

               End If

End Sub

''' <summary>

''' 09/08/2008 Edhy Rijo

''' Attempts to select the row index associated with the specified primary key

''' This method is used by EditChildRecord

''' This method should be use temporarily until the internal one in the listview

''' is made available by SF Team

''' </summary>

''' <param name="primaryKey"></param>

''' <remarks></remarks>

Private Sub SelectIndexByPrimaryKey(ByVal primaryKey As Object)

     For Each i As ListViewItem In Me.lstItems.Items

          If i.Tag.Equals(primaryKey) Then

               '-- Select the item

               i.Selected = True

               '-- Ensure this item is visible

               Me.lstItems.EnsureVisible(Me.lstItems.Items.IndexOf(i))

               '-- Nothing left to do

               Exit For

          End If

     Next

End Sub

By Juan Carlos Pazos - 3/24/2009

Hi Edji

The routine works great thanks. Just a simple question:

How do I exclude some fields from being copied? I did in a Maintenance form and works:

If col.ColumnName = Me.PublicacionesBO1.PrimaryKeyField Then

Continue For

End If

If col.ColumnName = Me.PublicacionesBO1.Ofertas Then

 Continue For

End If

... some other fields here

Me.PublicacionesBO1.CurrentRow(col) = copyRow(col)

But using the same logic in the ListView, the record is not copied.

Do you have some ideas?

Regards

By Edhy Rijo - 3/25/2009

Hi Juan Carlos,

Sorry, but I have no idea how to accomplish what you want. Maybe Trent or somebody else can jump in here.