C# .NET - hoe to merge the two dataset into one dataset in c#

Asked By karthik karthik
25-Aug-10 09:06 AM
hai friends


I am one dataset like this ds like  three columns this:
---------------------------------------------------
tblkey   Empkey    Empname
----------------------------------
T101   E10     Natraj
T102   E11     Siva
T103   E14    ganesh

I am having another dataset ds1 only two columns  like this:
---------------------------------------------------------------

Empkey   Empname
E10     karthi
E11     thriu
E13     maran

i waant merge the dataset and check the values  while checking  if ds is not having E13 it should bind and show the result like this  ds
tblkey   Empkey    Empname
----------------------------------
T101   E10     Natraj
T102   E11     Siva
T103   E14    ganesh
      E13     maran
here 'tblkey' comes empty
how to do in C# coding
  Mohan Raj Aryal replied to karthik karthik
25-Aug-10 02:17 PM
You can do Outer Join on EmpKey field. The result of full outer join combines both left and right outer joins. The joined table will contain all records from both tables, and fill in NULLs for missing matches on either side.

You can find how to do full join on two data tables on this http://www.codeproject.com/KB/cs/TwoDataTablesOuterJoin.aspx. 
  Ken Fitzpatrick replied to karthik karthik
25-Aug-10 04:16 PM
Karthik,

The following code will show you how to merge the data from the datasets. I added comments to help explain, but in a nutshell, you are going to loop through the data in the second dataset (the data you want to merge). For each item, simply search the first dataset for that item. If it doesn't exist in the first table, create a new row for the new item, populate the columns, and add the row to the table in the dataset. In order to search the first table, I show how you can do that with a dataview on the table in the forst dataset. The Dataview will allow you to call the find method on a primary field. Also, in my example, disregard the populateData function since you are already doing that. I had to add that to populate the datasets in my example with your data. Also, this example is a Console application. The concept is exactly the same whether it is a Windows Form, Web App, or console app. just don't use the Console.Writeline unless you are writing a console application. Here you go:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
  
namespace MergeDatasetExample
{
  class Program
  {
    static DataSet Dataset1 = new DataSet();
    static DataSet Dataset2 = new DataSet();
  
    static void Main(string[] args)
    {
      // Don't worry about this, just something I need to 
      // do to provide an example.
      populateDatasets();
  
      // Create a dataview for the table in Dataset1.
      // This will make it easy to search for values.
      // We need to sort on a field or an exception is
      // thrown. We will sort on the Empkey field.
      DataView dv = new DataView(Dataset1.Tables[0], "",
             "Empkey", DataViewRowState.CurrentRows);
      // Loop through all of the rows in the table in 
      // Dataset2 and add the ones not in Dataset1 to 
      // the table om Dataset2
      foreach (DataRow dr in Dataset2.Tables[0].Rows)
      {
        // See if we can find the Empkey value in the current 
        // row in the dataview. If so, then skip it, else add it
        if (dv.Find(dr["Empkey"]) == -1) 
        {
          DataRow newDr = Dataset1.Tables[0].NewRow();
          newDr["Empkey"] = dr["Empkey"];
          newDr["Empname"] = dr["Empname"];
          Dataset1.Tables[0].Rows.Add(newDr);
        }
      }
  
      //Display all rows in Dataset1 table[0].
      foreach (DataRow dr in Dataset1.Tables[0].Rows)
      {
        Console.WriteLine("tblkey: {0}, Empkey: {1}, Empname: {2}"
                  dr["tblkey"], dr["Empkey"], dr["Empname"]);
      }
  
      Console.ReadKey();
    }
  
    static void populateDatasets()
    {
      // Create columns for first table
      DataTable dt1 = new DataTable("Table1");
      DataColumn dc = new DataColumn("tblkey");
      dt1.Columns.Add(dc);
      dc = new DataColumn("Empkey");
      dt1.Columns.Add(dc);
      dc = new DataColumn("Empname");
      dt1.Columns.Add(dc);
  
      //Add rows to first table
      DataRow dr = dt1.NewRow();
      dr["tblkey"] = "T101";
      dr["Empkey"] = "E10";
      dr["Empname"] = "Natraj";
      dt1.Rows.Add(dr);
  
      dr = dt1.NewRow();
      dr["tblkey"] = "T102";
      dr["Empkey"] = "E11";
      dr["Empname"] = "Siva";
      dt1.Rows.Add(dr);
  
      dr = dt1.NewRow();
      dr["tblkey"] = "T103";
      dr["Empkey"] = "E14";
      dr["Empname"] = "ganesh";
      dt1.Rows.Add(dr);
  
      // Add Table1 to Dataset 1
      Dataset1.Tables.Add(dt1);
  
      // Create columns for second table
      DataTable dt2 = new DataTable("Table2");
      dc = new DataColumn("Empkey");
      dt2.Columns.Add(dc);
      dc = new DataColumn("Empname");
      dt2.Columns.Add(dc);
  
      //Add rows to second table
      dr = dt2.NewRow();
      dr["Empkey"] = "E10";
      dr["Empname"] = "karthi";
      dt2.Rows.Add(dr);
  
      dr = dt2.NewRow();
      dr["Empkey"] = "E11";
      dr["Empname"] = "thriu";
      dt2.Rows.Add(dr);
  
      dr = dt2.NewRow();
      dr["Empkey"] = "E13";
      dr["Empname"] = "maran";
      dt2.Rows.Add(dr);
  
      // Add Table2 to Dataset 2
      Dataset2.Tables.Add(dt2);
  
    }
  }
}

If you really want to understand this code, just create a console application and use debug to go through each line. That will really help your understanding.

Create New Account
help
I sometimes get the following error on my ASP.NET webpage. Server Error in ' / ' Application. - -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - DataTable internal index is corrupted: '5'. Description: An unhandled exception occurred during the execution of the information about the error and where it originated in the code. Exception Details: System.InvalidOperationException: DataTable internal index is corrupted: '5'. Source Error: An unhandled exception was generated during the execution of the exception can be identified using the exception stack trace below. Stack Trace: [InvalidOperationException: DataTable internal index is corrupted: '5'.] System.Data.RBTree`1.RBInsert(Int32 root_id, Int32 x_id, Int32 record, Boolean fireEvent) +64 System.Data.Index.ApplyChangeAction(Int32 record, Int32 action) +54 System.Data.DataTable.RecordStateChanged(Int32 record1, DataViewRowState oldState1, DataViewRowState newState1, Int32 record2, DataViewRowState oldState2, DataViewRowState newState2) +250 System.Data.DataTable.SetNewRecordWorker(DataRow row, Int32 proposedRecord, DataRowAction action, Boolean isInMerge, Int32
Verständnisfrage zu DataTable.GetChanges() .NET Framework Hallo NG, ich nutze zur Zeit die GetChanges() Methode um herauszufinden ob der User Änderungen an einem DataTable über ein DataGrid vorgenommen hat. Wechselt der User die Ansicht (den SQLString) soll er gefragt _dtAktuellTable = = null) { return false; } BindingContext[_dtAktuellTable].EndCurrentEdit(); / / complete any editing the user is currently doing DataTable changesDataTable = _dtAktuellTable.GetChanges(); / / dataTable Abrufen und Editirte DataRows mit Inhalt in der / / DatenBank vergleichen. ist nur eine Row unterschiedlich dann / / return true ansonsten am ende return false! if(changesDataTable ! = null){ try { DataTable dtAktuellInDb = new DataTable(); _dataAdapter.Fill(dtAktuellInDb); foreach (DataRow xRow in changesDataTable.Rows) { / / Suche diese Row in dem dtAktuellInDb Lieber einmal zuviel speichern als / / einmal zuwenig! return true; } } return false; } .NET Datenbank - German Discussions DataViewRowState.ModifiedCurrent (1) DataViewRowState (1) DataRowVersion.Original (1) DataRowVersion.Current (1) DataTable.GetChanges (1) DataRowVersion (1) DataColumn (1) DataTable
DataTable Issue n my prgoram I have 2 timer and 2 datatable.One datatable is common to both timers. When am trying to set the relation for both tables Data.DataRowCollection.get_Item(Int32 index) at System.Data.Index.InitRecords() at System.Data.Index. . ctor(DataTable table, Int32[] indexDesc, DataViewRowState recordStates, IFilter rowFilter, Boolean reusable) at System.Data.DataTable.GetIndex(Int32[] indexDesc, DataViewRowState recordStates, IFilter rowFilter) at System.Data.DataKey.GetSortIndex(DataViewRowState recordStates) at System.Data.DataRelation.GetParentRow(DataKey parentKey, DataKey childKey, DataRow childRow, DataRowVersion version) at
sSortExp = oDs.Tables[0].Columns[0].ToString(); DataRow[] aryDr = oDs.Tables[0].Select(sFilterExp, sSortExp, DataViewRowState.CurrentRows); die spalte in der tabelle ist vorhanden, wenn ich im Debugmodus nachsehen & sie hei XmlTests.Program.SortDataSetFromDatabase (1) System.Diagnostics.Debug.WriteLine (1) XmlTests.Program.SortDataSet (1) System.Data.DataTable.Select (1) DataViewRowState.CurrentRows (1) Visual Studio 2005 (1) OleDbDataAdapter (1) Hallo Martin, Am Sun, 14 Feb 2010 genannte Ausnahmefehler kann mehrere Ursachen haben. Die ersten sind relativ schnell zu ??berpr??fen: 1. DataTable.Columns null ist oder enth??lt keine Eintr??ge enth??lt. 2. DataTable.Columns[sSortExp] findet keine entspr. Spalte. Da die Zuweisung string sSortExp = oDs.Tables[0].Columns Fehlerquellen auszuschlie??en. 3. Nun gibst Du aber beim Aufrufen von Select() als letzten Parameter DataViewRowState.CurrentRows mit. Dies hat zur Folge, dass jede DataRow mit dem angegebenen DataViewRowState verglichen / evaluiert wird. Wenn die DataRow aber - aus welchen Gr??nden auch immer - *null* ist genau dem Fehlertext geworfen, den Du angegeben hast. Meine Frage: Kann es sein, dass deine DataTable eine DataRow = = null enth??lt? (Wie immer in solch obskuren F??llen ist es gut
HI A DataView enables you to create different views of the data stored in a DataTable , a capability that is often used in data-binding applications. Using a DataView , you can DTD / xhtml1-transitional.dtd " > <script runat = "server" > protected void Button1_Click( object sender, System.EventArgs e) { DataTable dt = new DataTable(); dt.TableName = "Books" ; DataColumn dc1 = new DataColumn(); dc1.ColumnName = "BookID" ; dc1.DataType = typeof ( int ); dc1.AllowDBNull = false ; dc1.Unique = true ; DataColumn dc2 = new DataColumn(); dc2.ColumnName = "Category" ; dc2.DataType = typeof ( string DataColumn dc3 = new DataColumn(); dc3.ColumnName = "BookName" ; dc3.DataType = typeof ( string ); DataColumn dc4 = new DataColumn(); dc4