Datatable.Merge doesn't work - c#

DataTable Table = CreateTableStucture();
DataTable Table_2 = Table.Clone();
Table.Rows.Add(0, "A", "B");
Table_2.Rows.Add(0, DBNull.Value, DBNull.Value, "C");
Table.Merge(Table_2);
Why after executing this code object:Table has row with values just from Table_2 and it's not merged as it should. These tables must have the same structure because my program requires it.
EDIT 1.
DataTable Table = new DataTable("table");
DataColumn KeyCol = new DataColumn("Key", typeof(int));
DataColumn Col1 = new DataColumn("col1", typeof(string));
DataColumn Col2 = new DataColumn("col2", typeof(string));
DataColumn Col3 = new DataColumn("col3", typeof(string));
DataColumn Col4 = new DataColumn("col4", typeof(string));
DataColumn Col5 = new DataColumn("col5", typeof(string));
Table.Columns.Add(KeyCol);
Table.Columns.Add(Col1);
Table.Columns.Add(Col2);
Table.Columns.Add(Col3);
Table.Columns.Add(Col4);
Table.Columns.Add(Col5);
Table.Constraints.Add("keyCon", KeyCol, true);
DataTable Table_2 = new DataTable();
Table_2 = Table.Clone();
Table.Rows.Add(0, "A", "B");
Table_2.Rows.Add(0, DBNull.Value, DBNull.Value, "C");
Table.Merge(Table_2);
Even that I create them this way it doesn't work.

The problem is you are having a primary key conflict.
DataColumn KeyCol = new DataColumn("Key", typeof(int));
//...
Table.Constraints.Add("keyCon", KeyCol, true);
//...
Table.Rows.Add(0, "A", "B");
Table_2.Rows.Add(0, DBNull.Value, DBNull.Value, "C");
You have a primary key of 0 for both rows, change the 2nd row to 1 and it should work.

You need to use Table.Copy() instead of Data.Clone()
From MSDN:
DataTable.Copy Copies both the structure and data for this DataTable.
DataTable.Clone Clones the structure of the DataTable, including all DataTable schemas
and constraints.

Related

Merge two datatables?

I want to merge two data table in which column "ID" as primary key in both table.
Note: Both table has two column as "ID, Name" & "ID, name" where Name & name is case sensitive.
Table: 1
Table: 2
Expected Merged Table Result:
Code:
public MainWindow()
{
InitializeComponent();
// Table 1
DataTable table1 = new DataTable();
table1.Columns.Add("ID", typeof(int));
table1.Columns.Add("Name", typeof(String));
table1.PrimaryKey = new DataColumn[] { table1.Columns["ID"] };
table1.Rows.Add(1, "A");
table1.Rows.Add(4, "D");
table1.Rows.Add(5, "E");
// Table 2
DataTable table2 = new DataTable();
table2.Columns.Add("ID", typeof(int));
table2.Columns.Add("name", typeof(String));
table2.PrimaryKey = new DataColumn[] { table2.Columns["ID"] };
table2.Rows.Add(1, "A");
table2.Rows.Add(2, "B");
table2.Rows.Add(3, "C");
table2.Rows.Add(5, "E");
table1.Merge(table2);
}
Please help me to achieve this expected result.
You could temporarily change the name of the second column and still use Merge:
const string OriginalName = "name";
const string TemporaryName = "temp";
table2.Columns[OriginalName].ColumnName = TemporaryName;
table1.Merge(table2);
table1.Columns[TemporaryName].ColumnName = OriginalName;
table2.Columns[TemporaryName].ColumnName = OriginalName;
Use this:
DataTable dtResult = new DataTable();
dtResult.Columns.Add("ID", typeof(int));
dtResult.Columns.Add("Name", typeof(string));
dtResult.Columns.Add("name", typeof(string));
var result = from dataRows1 in table1.AsEnumerable()
join dataRows2 in table2.AsEnumerable()
on dataRows1.Field<int>("ID") equals dataRows2.Field<int>("ID")
into rows
from row in rows.DefaultIfEmpty()
select dtResult.LoadDataRow(new object[]
{
dataRows1.Field<int>("ID"),
dataRows1.Field<string>("Name"),
dataRows2.Field<string>("name")
}, false);

How do I add a ListBox item to a DataGridView column header [duplicate]

How do create a DataTable in C#?
I did like this:
DataTable dt = new DataTable();
dt.clear();
dt.Columns.Add("Name");
dt.Columns.Add("Marks");
How do I see the structure of DataTable?
Now I want to add ravi for Name and 500 for Marks. How can I do this?
Here's the code:
DataTable dt = new DataTable();
dt.Clear();
dt.Columns.Add("Name");
dt.Columns.Add("Marks");
DataRow _ravi = dt.NewRow();
_ravi["Name"] = "ravi";
_ravi["Marks"] = "500";
dt.Rows.Add(_ravi);
To see the structure, or rather I'd rephrase it as schema, you can export it to an XML file by doing the following.
To export only the schema/structure, do:
dt.WriteXMLSchema("dtSchemaOrStructure.xml");
Additionally, you can also export your data:
dt.WriteXML("dtDataxml");
You can also pass in an object array as well, like so:
DataTable dt = new DataTable();
dt.Clear();
dt.Columns.Add("Name");
dt.Columns.Add("Marks");
object[] o = { "Ravi", 500 };
dt.Rows.Add(o);
Or even:
dt.Rows.Add(new object[] { "Ravi", 500 });
Create DataTable:
DataTable MyTable = new DataTable(); // 1
DataTable MyTableByName = new DataTable("MyTableName"); // 2
Add column to table:
MyTable.Columns.Add("Id", typeof(int));
MyTable.Columns.Add("Name", typeof(string));
Add row to DataTable method 1:
DataRow row = MyTable.NewRow();
row["Id"] = 1;
row["Name"] = "John";
MyTable.Rows.Add(row);
Add row to DataTable method 2:
MyTable.Rows.Add(2, "Ivan");
Add row to DataTable method 3 (Add row from another table by same structure):
MyTable.ImportRow(MyTableByName.Rows[0]);
Add row to DataTable method 4 (Add row from another table):
MyTable.Rows.Add(MyTable2.Rows[0]["Id"], MyTable2.Rows[0]["Name"]);
Add row to DataTable method 5 (Insert row at an index):
MyTable.Rows.InsertAt(row, 8);
// Create a DataTable and add two Columns to it
DataTable dt=new DataTable();
dt.Columns.Add("Name",typeof(string));
dt.Columns.Add("Age",typeof(int));
// Create a DataRow, add Name and Age data, and add to the DataTable
DataRow dr=dt.NewRow();
dr["Name"]="Mohammad"; // or dr[0]="Mohammad";
dr["Age"]=24; // or dr[1]=24;
dt.Rows.Add(dr);
// Create another DataRow, add Name and Age data, and add to the DataTable
dr=dt.NewRow();
dr["Name"]="Shahnawaz"; // or dr[0]="Shahnawaz";
dr["Age"]=24; // or dr[1]=24;
dt.Rows.Add(dr);
// DataBind to your UI control, if necessary (a GridView, in this example)
GridView1.DataSource=dt;
GridView1.DataBind();
To add a row:
DataRow row = dt.NewRow();
row["Name"] = "Ravi";
row["Marks"] = 500;
dt.Rows.Add(row);
To see the structure:
Table.Columns
You can add Row in a single line
DataTable table = new DataTable();
table.Columns.Add("Dosage", typeof(int));
table.Columns.Add("Drug", typeof(string));
table.Columns.Add("Patient", typeof(string));
table.Columns.Add("Date", typeof(DateTime));
// Here we add five DataRows.
table.Rows.Add(25, "Indocin", "David", DateTime.Now);
table.Rows.Add(50, "Enebrel", "Sam", DateTime.Now);
table.Rows.Add(10, "Hydralazine", "Christoff", DateTime.Now);
table.Rows.Add(21, "Combivent", "Janet", DateTime.Now);
table.Rows.Add(100, "Dilantin", "Melanie", DateTime.Now);
You can write one liner using DataRow.Add(params object[] values) instead of four lines.
dt.Rows.Add("Ravi", "500");
As you create new DataTable object, there seems no need to Clear DataTable in very next statement. You can also use DataTable.Columns.AddRange to add columns with on statement. Complete code would be.
DataTable dt = new DataTable();
dt.Columns.AddRange(new DataColumn[] { new DataColumn("Name"), new DataColumn("Marks") });
dt.Rows.Add("Ravi", "500");
The easiest way is to create a DtaTable as of now
DataTable table = new DataTable
{
Columns = {
"Name", // typeof(string) is implied
{"Marks", typeof(int)}
},
TableName = "MarksTable" //optional
};
table.Rows.Add("ravi", 500);
DataTable dt=new DataTable();
Datacolumn Name = new DataColumn("Name");
Name.DataType= typeoff(string);
Name.AllowDBNull=false; //set as null or not the default is true i.e null
Name.MaxLength=20; //sets the length the default is -1 which is max(no limit)
dt.Columns.Add(Name);
Datacolumn Age = new DataColumn("Age", typeoff(int));`
dt.Columns.Add(Age);
DataRow dr=dt.NewRow();
dr["Name"]="Mohammad Adem"; // or dr[0]="Mohammad Adem";
dr["Age"]=33; // or dr[1]=33;
dt.add.rows(dr);
dr=dt.NewRow();
dr["Name"]="Zahara"; // or dr[0]="Zahara";
dr["Age"]=22; // or dr[1]=22;
dt.rows.add(dr);
Gv.DataSource=dt;
Gv.DataBind();
DataTable dt=new DataTable();
DataColumn Name = new DataColumn("Name",typeof(string));
dt.Columns.Add(Name);
DataColumn Age = new DataColumn("Age", typeof(int));`
dt.Columns.Add(Age);
DataRow dr=dt.NewRow();
dr["Name"]="Kavitha Reddy";
dr["Age"]=24;
dt.add.Rows(dr);
dr=dt.NewRow();
dr["Name"]="Kiran Reddy";
dr["Age"]=23;
dt.Rows.add(dr);
Gv.DataSource=dt;
Gv.DataBind();
You have to add datarows to your datatable for this.
// Creates a new DataRow with the same schema as the table.
DataRow dr = dt.NewRow();
// Fill the values
dr["Name"] = "Name";
dr["Marks"] = "Marks";
// Add the row to the rows collection
dt.Rows.Add ( dr );
In addition to the other answers.
If you control the structure of the DataTable there is a shortcut for adding rows:
// Assume you have a data table defined as in your example named dt
dt.Rows.Add("Name", "Marks");
The DataRowCollection.Add() method has an overload that takes a param array of objects. This method lets you pass as many values as needed, but they must be in the same order as the columns are defined in the table.
So while this is a convenient way to add row data, it can be risky to use. If the table structure changes your code will fail.
Question 1: How do create a DataTable in C#?
Answer 1:
DataTable dt = new DataTable(); // DataTable created
// Add columns in your DataTable
dt.Columns.Add("Name");
dt.Columns.Add("Marks");
Note: There is no need to Clear() the DataTable after creating it.
Question 2: How to add row(s)?
Answer 2: Add one row:
dt.Rows.Add("Ravi","500");
Add multiple rows: use ForEach loop
DataTable dt2 = (DataTable)Session["CartData"]; // This DataTable contains multiple records
foreach (DataRow dr in dt2.Rows)
{
dt.Rows.Add(dr["Name"], dr["Marks"]);
}
Create datatabe with 2 columns: Name & Marks
IList columns = new List() {"Name", "Marks"};
Datatabel dt = new Datatable();
foreach (string column in columns)
dtSalesOrder.Columns.Add(column, typeof(string));
Add data to datatable
dt.Rows.Add("Ravi","500");

How to merge two data tables with same names but they are case sensitive?

I am getting dynamic data from two sources. The column names are same but have different casing. While merging data tables it will create duplicate columns. I want to merge with same columns, regardless of the casing.
Code:
dataTable1.merge(dataTable2);
My column names in dataTable1 are:
Title
filePath
My column names in dataTable2 are:
title
FilePath
It should consider these two columns as identical.
MyCode:
public void TestOnMergeDataTables()
{
DataTable dt = new DataTable("Order");
DataColumn dc = dt.Columns.Add("ID", typeof(int));
dt.Columns.Add("Name", typeof(String));
dt.Rows.Add(1, "pramod");
dt.Rows.Add(2, "ravi");
dt.Rows.Add(3, "deepak");
dt.Rows.Add(4, "kiran");
dt.Rows.Add(5, "madhu");
DataTable dt2 = new DataTable("Order");
DataColumn dc2 = dt2.Columns.Add("ID", typeof(int));
dt2.Columns.Add("name", typeof(String));
dt2.Columns.Add("Type", typeof(String));
dt2.Rows.Add(6, "ashu", "Gen");
dt2.Rows.Add(7, "rudra", "Gen");
dt2.Rows.Add(8, "kavita", "Gen");
dt2.Rows.Add(9, "suman", "Gen");
dt2.Rows.Add(10, "lakshman", "Gen");
dt.Merge(dt2,true);
}
Result:
Output of the program
it should treat Name , name columns as same column
A simple way can be using linq. (This won't remove duplicates present in the columns). For removing duplicates, you have to use GroupBy.
var mergedTable = dataTable1.AsEnumerable()
.Select(row => new { Key = dataRow["Title"], Row = dataRow })
.Union(dataTable1.AsEnumerable()
.Select(row => new { Key = dataRow["title"], Row = dataRow }))
.CopyToDataTable();

GridView from 2 DataTables

I have a dataset contains 2 datatables with a relation between them,
in the first table i have an ID (primary key) and MainAreaName and in the second table I have the ID from the first table with 2 other columns
the question is: how to view the MainAreaName from the first table with the other 2 columns from the second table in a gridview
DataSet MyDB = new DataSet("MyDB");
DataTable MainArea = new DataTable("MainArea");
DataTable NameNumber = new DataTable("NameNumber");
DataColumn Col01 = new DataColumn("ID", typeof(int));
Col01.AutoIncrement = true;
Col01.AutoIncrementSeed = 1;
Col01.AutoIncrementStep = 1;
DataColumn Col02 = new DataColumn("MainAreaName", typeof(string));
MainArea.Columns.Add(Col01);
MainArea.Columns.Add(Col02);
MainArea.PrimaryKey =
new DataColumn[] { MainArea.Columns["ID"] };
DataRow MyRow = MainArea.NewRow();
MyRow["MainAreaName"] = "Area1";
MainArea.Rows.Add(MyRow);
MyRow = MainArea.NewRow();
MyRow["MainAreaName"] = "Area2";
MainArea.Rows.Add(MyRow);
DataColumn Col11 = new DataColumn("MainAreaID", typeof(int));
DataColumn Col12 = new DataColumn("Name", typeof(string));
DataColumn Col13 = new DataColumn("Number", typeof(int));
DataColumn Col14 = new DataColumn("Comment", typeof(string));
NameNumber.Columns.Add(Col11);
NameNumber.Columns.Add(Col12);
NameNumber.Columns.Add(Col13);
NameNumber.Columns.Add(Col14);
NameNumber.PrimaryKey =
new DataColumn[] {
NameNumber.Columns["MainAreaID"], NameNumber.Columns["Number"] };
NameNumber.Rows.Add(1, "Test1", 67);
NameNumber.Rows.Add(1, "Test2", 87);
NameNumber.Rows.Add(2, "Test3", 77);
NameNumber.Rows.Add(2, "Test4", 88);
MyDB.Tables.Add(MainArea);
MyDB.Tables.Add(NameNumber);
MyDB.Relations.Add(
MyDB.Tables["MainArea"].Columns["ID"],
MyDB.Tables["NameNumber"].Columns["MainAreaID"]);
I tried to use the following code
DataRelation DR = new DataRelation("MainAreaRelation", MyDB.Tables["MainArea"].Columns["ID"], MyDB.Tables["NameNumber"].Columns["MainAreaID"]);
dataGridView1.DataSource = MyDB.Relations["MainAreaRelation"].ParentTable;
//or
dataGridView1.DataSource = MyDB.Relations["MainAreaRelation"].ParentTable;
but didn't work,
anyone can help please?

how to insert data to dataset

i have this making table:
DataTable WorkTbl()
{
DataTable Work= new DataTable("Work"); //Table Name
DataColumn MAC = new DataColumn("MAC", typeof(string));
DataColumn ID_OLD = new DataColumn("ID_OLD", typeof(string));
Work.Columns.Add(MAC);
Work.Columns.Add(ID_OLD);
return Work;
}
how to insert data to this table and how to convert this table to Dataset ?
thanks in advance
From MSDN:
DataRow workRow = workTable.NewRow();
You then can manipulate the newly added row using an index or the column name, as shown in the following example.
workRow["CustLName"] = "Smith";
workRow[1] = "Smith";
DataSet customerOrders = new DataSet("CustomerOrders");
DataTable ordersTable = customerOrders.Tables.Add("Orders");
DataColumn pkOrderID =
ordersTable.Columns.Add("OrderID", typeof(Int32));
ordersTable.Columns.Add("OrderQuantity", typeof(Int32));
ordersTable.Columns.Add("CompanyName", typeof(string));
ordersTable.PrimaryKey = new DataColumn[] { pkOrderID };

Categories

Resources