C# MYSQL find DataTable.PrimaryKey in another DataTable? - c#

i have 2 DataTables with Data (dtm and dtl).
I must find out if exist a DataRow from DataTable1 in Datatable2.
I have a combined primray key of 3 columns.
I know that i can get the DataTable primarykey like this.
DataColumn[] pkcol;
pkcol = dtm.PrimaryKey;
Is it possible to use the Find method like this?
if (dtl.Rows.Find(dtm[pkcol]) == null)
{
}
I must realize an DataTable Sync Method.
So i go foreach Datarow in dtm.Rows and Foreach Datarow in dtl.Rows.
It would be great if i can go ahead over the table and search for if exist the datarows primary key value in the table.
Any ideas?
Please help.
Thanks

According to MSDN DataRowCollection.Findalready is looking for rows with the given values in the PKs. So you don't even need to get the PKs, but simply an array of values, that matches the PKs in number and type:
// Create an array for the key values to find.
object[]findTheseVals = new object[3];
// Set the values of the keys to find.
findTheseVals[0] = "John";
findTheseVals[1] = "Smith";
findTheseVals[2] = "5 Main St.";
DataRow foundRow = table.Rows.Find(findTheseVals);
You would set the values to null to find your row.

Related

Column abc does not belong to table?

I am iterating a DataTable in my C# code. I try to get the contents using of a column named "columnName" of row named "row" using -
object value = row["ColumnName"];
I get this error -
Error: System.Reflection.TargetInvocationException: Exception has been
thrown by the target of an invocation.
---> System.ArgumentException: Column 'FULL_COUNT' does not belong to table . at System.Data.DataRow.GetDataColumn(String columnName)
How is this possible ? My SQL query/result set has a column by that name and the query even runs in management studio.
How do I fix this error ?
I am guessing your code is iteration supposed to be something like this
DataTable table = new DataTable();
foreach (DataRow row in table.Rows) {
foreach (DataColumn col in table.Columns) {
object value = row[col.ColumnName];
}
}
If this is the case, row["ColumnName"] in each iteration looks for the same column with name ColumnName which obviously does not exists in your table.
The correct way is row[ColumnName] or row[col.ColumnName] in iteration above
I had a similar issue on my c# code, using a dataset which I had successfully initialized and populated with data from the DB.
So my return set was:
data = new Byte[0];
data = (Byte[])(dataset.Tables[0].Rows[0]["systemLogo_img"]);
Of course the error was in t finding the column 'systemLogo_img'.
I noted that you simply do NOT have to call /qualify the column name. So the correction is:
data = new Byte[0];
data = (Byte[])(dataset.Tables[0].Rows[0].ItemArray[0]);
Simply put: use "ItemArray" at position.
Thanks
Do not write Gridview column names instead of Database column names.
dataGridViewEmployeeClass.Rows[n].Cells[0].Value = item["write the Database Column names"].ToString();
Try this, make sure your column name is same
DataTable dt = new DataTable();
dt.Columns.Add("abc", typeof(string));
DataRow dr = dt.NewRow();
dr["abc"]="";
I had a similar issue which was very basic to fix.
I was querying with a specific column name rather than Select * (i.e. Select Title). Beginner's error but happens to everyone.
If you want to check if the column exists in the DataRow before accessing the value the following block can help...
if (dataRow.Table.Columns.Contains("theColumnName"))
{
// do work
string text = string.Empty;
if (dataRow["theColumnName"] != System.DBNull.Value)
{
text = Convert.ToString(dataRow["theColumnName"]);
}
}
If it doesn't exist and it needs to be added to the data table you can add the column using #Karthick Ganesan's example
// add a column
dataTable.Columns.Add("theColumnName", typeof(string));
I had same issue was trying to pass two different keys for same product.
item.Product = SqlHelper.GetSafeString(dr, "ProductName");
item.Product = SqlHelper.GetSafeString(dr, "Product");

Adding a column from one Datatable to another datatable of a dataset [duplicate]

How can I copy 1 data column from 1 data table to a new datatable. When I try to do it, I get the error Column 'XXX' already belongs to another DataTable.?
dataColumn = datatable1.Columns[1];
datatable2 = new DataTable();
datatable2.Columns.Add(dataColumn);
Thanks in Advance
You cannot copy DataColumns. What you'll need to do is create a new DataColumn in the new datatable with the same data type as in the old datatable's column, and then you need to run a FOR loop to bring in all the data from the old datatable to the new datatable.
See the following code. This assumes that the datatables have exactly the same number of rows.
DataTable dt1 = new DataTable();
DataTable dt2 = new DataTable();
dt2.Columns.Add("ColumnA", dt1.Columns["ColumnA"].DataType);
for (int i = 0; i < dt1.Rows.Count; i++)
{
dt2.Rows[i]["ColumnA"] = dt1.Rows[i]["ColumnA"];
}
Also, If the data you are copying are reference types and not value types you might want to see if a .Clone() method is available for the type, or make one yourself. Just doing 'this = that' in the FOR loop will not work on reference types.
You cannot copy a DataColumn. (DataColumns are very tightly coupled with their tables)
Instead, you can add a new column with the same name and datatype.
You might be looking for DataTable.Clone(), which will create a structual copy of an entire table. (With the same schema, but no data)
Just a thought, are your DataTables both in the same DataSet?
If so, you can create a named DataRelation between the columns of two tables (think foreign key).
Then you can add a Calculated DataColumn to your table that has its Expression property set to "Child(RelationName).ColumnName" or "Parent(RelationName).ColumnName" depending on the direction of the relationship.
This will give you the same effect as copying the column, but I believe it only evaluates it lazily. So maybe it will give you what you need.
There is an example here of how this works. The example uses the Sum aggregate function, but you just need to reference the column name and it will duplicate it in your DataTable
myDataSet.Relations.Add(
"Orders2OrderLines",
myDataSet.Tables["Orders"].Columns["OrderID"],
myDataSet.Tables["OrderLines"].Columns["OrderID"]);
ordersTable.Columns.Add("OrderTotal", typeof(decimal), "Sum(Child(Orders2OrderLines).ExtendedPrice)");
HTH
The problem is caused by the c# can not reuse the object instance created and uses it on multiples DataTables. For this it is necessary to create a new object DataCollumn for each loop iteration.
foreach (DataTable table in DATASET.Tables)
{
DataColumn yourDataCollumn = new DataColumn("Name of DataCollumn", typeof(Your data type));
// your logic here
}
Hope it's help...
I used the below to merge two tables using mostly LINQ and only looping through the rows at the end. I wouldn't call it pretty but it does work. Using the join to prevent some of the assumptions listed above.
DataTable tableOne = getTableOne();
DataTable tableTwo = getTableTwo();
var oneColumns = tableOne.Columns.Cast<DataColumn>()
.Select(p => new Column(p.ColumnName, DataType))
.ToArray();
var twoColumns = tableTwo.Columns.Cast<DataColumn>()
.Select(p => new DataColumn(p.ColumnName, p.DataType))
.ToArray();
var matches = (from a in tableOne.AsEnumerable()
join b in tableTwo.AsEnumerable() on a["column_name"] equals b["column_name"]
select a.ItemArray.Concat(b.ItemArray)).ToArray();
DataTable merged = new DataTable();
merged.Columns.AddRange(oneColumns);
merged.Columns.AddRange(twoColumns);
foreach (var m in matches) { merged.Rows.Add(m.ToArray()); }
No looping required , Refer this , Hope this should solve your problem...
DataTable dt = new DataTable();
//fill the dt here
DataTable dt2 = new DataTable();
string[] strCols = {"Column Name to copy"};
dt2 = dt.DefaultView.ToTable("newTableName", false, strCols);

How to copy all the rows in a datatable to a datarow array?

I have two tables:
tbl_ClassFac:
ClassFacNo (Primary Key)
,FacultyID
,ClassID
tbl_EmpClassFac:
EmpID, (Primary Key)
DateImplement, (Primary Key)
ClassFacNo
I want to know all the Employees who are on a specific ClassFacNo. ie. All EmpID with a specific ClassFacNo... What I do is that I first search tbl_EmpClassFac with the EmpID supplied by the user. I store these datarows. Then use the ClassFacNo from these datarows to search through tbl_ClassFac.
The following is my code.
empRowsCF = ClassFacDS.Tables["EmpClassFac"].Select("EmpID='" + txt_SearchValueCF.Text + "'");
int maxempRowsCF = empRowsCF.Length;
if (maxempRowsCF > 0)
{
foundempDT = ClassFacDS.Tables["ClassFac"].Clone();
foreach (DataRow dRow in empRowsCF)
{
returnedRowsCF = ClassFacDS.Tables["ClassFac"].Select("ClassFacNo='" + dRow[2].ToString() + "'");
foundempDT.ImportRow(returnedRowsCF[0]);
}
}
dataGrid_CF.DataSource = null;
dataGrid_CF.DataSource = foundempDT.DefaultView;
***returnedRowsCF = foundempDT.Rows;*** // so NavigateRecordsCF can be used
NavigateRecordsCF("F"); // function to display data in textboxes (no importance here)
I know the code is not very good but that is all I can think of. If anyone has any suggestions please please tell me. If not tell me how do I copy all the Rows in a datatable to a datarow array ???
"How to copy all the rows in a datatable to a datarow array?"
If that helps, use the overload of Select without a parameter
DataRow[] rows = table.Select();
DataTable.Select()
Gets an array of all DataRow objects.
According to the rest of your question: it's actually not clear what's the question.
But i assume you want to filter the first table by a value of a field in the second(related) table. You can use this concise Linq-To-DataSet query:
var rows = from cfrow in tbl_ClassFac.AsEnumerable()
join ecfRow in tbl_EmpClassFac.AsEnumerable()
on cfrow.Field<int>("ClassFacNo") equals ecfRow.Field<int>("ClassFacNo")
where ecfRow.Field<int>("EmpId") == EmpId
select cfrow;
// if you want a new DataTable from the filtered tbl_ClassFac-DataRows:
var tblResult = rows.CopyToDataTable();
Note that you can get an exception at CopyToDataTable if the sequence of datarows is empty, so the filter didn't return any rows. You can avoid it in this way:
var tblResult = rows.Any() ? rows.CopyToDataTable() : tbl_ClassFac.Clone(); // empty table with same columns as source table

How to get unique records of specific columns of data table

I have a DataTable imported from Excel file.
Data i need is only unique from specific columns of the DataTable.
The unique data i meant is like when a command DISTINCT is used in SQL Select Query.
I want to get the list of the unique data from the DataTable Column and put them into List
I think LinQ can be used for this matter but i'm not so familiar with it.
I was thinking of code like this below
var data is from MyDataTable
where MyDataTable.ColumnName = "SpecificColumn"
select MyDataTable["SpecificColumn"]).UniqueData;
List<string> MyUniqueData = new List<string>();
foreach(object obj in data)
{
if(MyUniqueData.NotContain(obj))
MyUniqueData.add(obj);
}
I hope someone can drop off some knowledge to me.
var unique = data.Distinct().ToList();
What you're looking for is .Distinct(). See MSDN documentation here. You can specify your own comparer if you need something specific and it will return only unique records.
If you have a Datatable or DataView, inorder to get unique records from a column, you have to write this.
this would be simple.
DataTable dtNew = dt.DefaultView.ToTable(true, "ColName"); // for Datatable
DataTable dtnew= dv.ToTable(true, "ColName"); // for DataView

How can I add the column data type after adding the column headers to my datatable?

Using the code below (from a console app I've cobbled together), I add seven columns to my datatable. Once this is done, how can I set the data type for each column? For instance, column 1 of the datatable will have the header "ItemNum" and I want to set it to be an Int. I've looked at some examples on thet 'net, but most all of them show creating the column header and column data type at once, like this:
loadDT.Columns.Add("ItemNum", typeof(Int));
At this point in my program, the column already has a name. I just want to do something like this (not actual code):
loadDT.Column[1].ChangeType(typeof(int));
Here's my code so far (that gives the columns their name):
// get column headings for datatable by reading first line of csv file.
StreamReader sr = new StreamReader(#"c:\load_forecast.csv");
headers = sr.ReadLine().Split(',');
foreach (string header in headers)
{
loadDT.Columns.Add(header);
}
Obviously, I'm pretty new at this, but trying very hard to learn. Can someone point me in the right direction? Thanks!
You should be able to assign the column's data type property so long as there is no data stored in that column yet:
CODE:
loadDT.Column[1].DataType = typeof(int);
visual studio not allows to change type of a column has some data,
u must create a new column with ur ideal type and copy data from specified column to new column
DataTable DT = new DataTable();
DT = somsdata ;
DT.columns.Add("newcol",object);
foreach(datarow dr in DT.rows)
dr.itemarray["newcolumn"] = dr.itemarray["oldColumn"];

Categories