Link to home
Start Free TrialLog in
Avatar of mromeo
mromeo

asked on

Why does DataSet Merge add a new row instead of updating an existing row?

I have a DataSet that can be updated when someone updates a DataGrid.  After the update, I want to Merge the changes from the DataGrid's DataSet to another DataSet. Here is some sample code:

     DataSet ds = (DataSet)dataGrid1.DataSource;
     ds.AcceptChanges();
     DataSet dsClone = ds.Copy();
     dsClone.AcceptChanges();

     DataRow dr = ds.Tables[0].Rows[dataGrid1.CurrentRowIndex];
     dr["subject"] = "hello";
               
     DataSet changes = ds.GetChanges();
     ds.AcceptChanges();

     if (changes != null)
     {
          dsClone.Merge(changes, false, MissingSchemaAction.Error);
          dsClone.AcceptChanges();
     }

     
After this code is executed, I end up with an extra row in the cloned DataSet and the row does not get updated.  The DataSet was created from an XML file shown below.  I did a DataSet.ReadXML and then the DataGrid's DataSource member was set to the DataSet.  The XML has a primary key (msgId).


<?xml version="1.0" standalone="yes"?>
<MessageList xmlns="http://tempuri.org/Messages.xsd">
  <Msg>
    <msgId>10</msgId>
    <descr>Yesterday</descr>
    <subject>some subject</subject>
    <msgText versionNo ="1.0">disk is full</msgText>
  </Msg>
  <Msg>
    <msgId>5</msgId>
    <descr>Message #1</descr>
    <subject>some other subject</subject>
    <msgText versionNo="1.0">The message goes here</msgText>
  </Msg>
  </MessageList>

How can I get the DataSet to UPDATE the row as opposed to adding a brand new row when I call Merge?

THANKS!
Avatar of rajaloysious
rajaloysious

You may have not set a primary key.
Try setting a primary key and check this..

cheers
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfsystemdatadatasetclassmergetopic2.asp
says so:
When merging a new source DataSet into the target, any source rows with a DataRowState value of Unchanged, Modified, or Deleted, are matched to target rows with the same primary key values. Source rows with a DataRowState value of Added are matched to new target rows with the same primary key values as the new source rows.

cheers
Avatar of mromeo

ASKER

My xml has a primary key.   The primary key is msgId.  If it has a primary key, shouldn't it match it up against the same record?  Do you need to see the schema?
ASKER CERTIFIED SOLUTION
Avatar of rajaloysious
rajaloysious

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of mromeo

ASKER

Yes, that it did it!! Thanks.  You need to make sure you specify the primary key in BOTH the source and target.