How to copy all rows in datatable to 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. i.e. All EmpIDs with a specific ClassFacNo ... What I do is that I first look for tbl_EmpClassFac with the EmpID provided by the user. I keep these datarows. Then use ClassFacNo from these datarows to search on tbl_ClassFac. Below 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 isn't very good, but that's all I can think of. If anyone has any suggestions please tell me. Unless you tell me how do I copy all the rows in the datatable to the datarow array ???
"How to copy all rows in datatable to datarow array?"
If it helps, use Select
parameterless overloading
DataRow[] rows = table.Select();
DataTable.Select()
Gets an array of all DataRow objects.
Consistent with the rest of your question: It's not really clear what the question is.
But I am assuming that you want to filter the first table based on the field value in the second (linked) 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 CopyToDataTable
if the datarows sequence is empty, so the filter doesn't return any rows. You can avoid this with the following:
var tblResult = rows.Any() ? rows.CopyToDataTable() : tbl_ClassFac.Clone(); // empty table with same columns as source table