Programming Journal C#, Java, SQL and to a lesser extent HTML, CSS, XML, and regex. I made this so other programmers could benefit from my experience.

Thursday, October 4, 2007

Using a GridView to make calculations and avoid Database changes by merging DataTables and using PrimaryKey.

Merging DataTables named dt and dt2.

Before I show the diffences, here are the contents of dt (Figure 1) and dt2 (Figure 2):

Symbol Name Exchange
FRE Freddie Mac NYSE
FRE/PB Freddie Mac NYSE
FRE/PF Freddie Mac NYSE
FRE/PG Freddie Mac NYSE
FRE/PH Freddie Mac NYSE
Figure 1. dt

Symbol EPS Growth Lower Price Target Lower % Target Upper Price Target Upper % Target
FRE FRE FRE FRE FRE FRE
FRE/PB FRE/PB FRE/PB FRE/PB FRE/PB FRE/PB
FRE/PF FRE/PF FRE/PF FRE/PF FRE/PF FRE/PF
FRE/PG FRE/PG FRE/PG FRE/PG FRE/PG FRE/PG
FRE/PH FRE/PH FRE/PH FRE/PH FRE/PH FRE/PH
Figure 2. dt2

In my project I want to use a GridView and append calculated data without changing the database.
My solution is to read the GridView into a DataTable, dt. Then, I make calculations from a PrimaryKey of dt and use the same PrimaryKey for dt2 while adding actual calculations (EPS Growth, Lower Price Target, ... in production version). The final step is to Merge the datatables with dt.Merge(dt2). The result is shown in Figure 3.

Symbol Name Exchange EPS Growth Lower Price Target Lower % Target Upper Price Target Upper % Target
FRE Freddie Mac NYSE FRE FRE FRE FRE FRE
FRE/PB Freddie Mac NYSE FRE/PB FRE/PB FRE/PB FRE/PB FRE/PB
FRE/PF Freddie Mac NYSE FRE/PF FRE/PF FRE/PF FRE/PF FRE/PF
FRE/PG Freddie Mac NYSE FRE/PG FRE/PG FRE/PG FRE/PG FRE/PG
FRE/PH Freddie Mac NYSE FRE/PH FRE/PH FRE/PH FRE/PH FRE/PH
Figure 3.

If you simply Merge with dt.Merge(dt2), you would get the same result as long as the PrimaryKey is set in dt. However, without setting the PrimaryKey you get the result in Figure 4.

Symbol Name Exchange EPS Growth Lower Price Target Lower % Target Upper Price Target Upper % Target
FRE Freddie Mac NYSE
FRE/PB Freddie Mac NYSE
FRE/PF Freddie Mac NYSE
FRE/PG Freddie Mac NYSE
FRE/PH Freddie Mac NYSE
FRE FRE FRE FRE FRE FRE
FRE/PB FRE/PB FRE/PB FRE/PB FRE/PB FRE/PB
FRE/PF FRE/PF FRE/PF FRE/PF FRE/PF FRE/PF
FRE/PG FRE/PG FRE/PG FRE/PG FRE/PG FRE/PG
FRE/PH FRE/PH FRE/PH FRE/PH FRE/PH FRE/PH
Figure 4.

In my implementation I use:
dt.Merge(dt2, false, MissingSchemaAction.Ignore);
This will avoid preserving changes and ignore taking action when there is a missing schema.

1 comment:

Anonymous said...

Its all in the manual they make you read before they download your being into those tiny bodies in those dark wombs.