select query with contain condition in datatable using c# - c#

I have a datatable and i need to put CONTAINS condition in it.Now am retrieving datatable rows using below query
DataRow[] resultss = dtDocument.Select("DocumentElementText='" + columnValue + "'");
but i need to put condition like contains in this query for retrieving values from datatable.
above is my datatable. this query dtDocument.Select("DocumentElementText='New Package'"); will return me the first row from the datatable.What i need is , i need to retrieve the row which contains <td>NAME</td> from this datatable. How to retrieve the row ..??
Regards
Arshad

try this
DataRow[] resultss = dt.AsEnumerable().Where(row => row.Field<string>("DocumentElementText").Contains("Enter Your String Here")).Select(row => row).ToArray<DataRow>();

Related

find and display datarows in datagridview

I faced to issue of displaying datarows from DataTable from DataSet. I used a temporary table. I found rows that I need by id and copy it to temporary table and then diplay in DataGridView. Is there any way to find and display rows that I need in DataGridView directly from DataTable from DataSet without using any temporary DataTable's? I've tried to do this by hiding and unhiding rows in DataGridView, but sadly it didn't worked out
private DataTable tblFiltered =
ds.Tables("GRAPHICS").AsEnumerable().Where(row =>
row.Field<int>("GRAPHIC_ID") == graphId && row.Field<int>
("GRAPHIC_ID")).CopyToDataTable;
Assuming that DataSet 'ds' containing Table 'GRAPHICS',We can use DataView to Display filtered records in DataGridView. Ex.
int graphId = 2; //Assuming
DataView dv = ds.Tables["GRAPHICS"].AsDataView();
dv.RowFilter = "GRAPHIC_ID = " + graphId; //RowFilter :: Expression used to filter which rows are viewed !!
dataGridView.DataSource = dv.ToTable();
You can use filter
(DatagridView.DataSource as DataTable).DefaultView.RowFilter = string.Format("GRAPHIC_ID= '{0}'", graphId);

How To select Specific Column From DataTable in C#?

I have a dataTable with 4 columns ,
I want to select one column without foreach or any other expensive loop and my result must be a new data table with one column ,How can I do this;
DataTable leaveTypesPerPersonnel = LeaveGroup.GetLeaveTypesPerPersonnels(dtPersonnel.row);
leaveTypesPerPersonnel has this columns :
[ID,Guid,LeaveTypeID,Code]
I want Filter leaveTypesPerPersonnel wihtout foreach and get new datatable with just Column [ID]
NOTE: Output must be a Datatable With one column.
leaveTypesPerPersonnel.Columns.Remove("Guid");
leaveTypesPerPersonnel.Columns.Remove("LeaveTypeID");
leaveTypesPerPersonnel.Columns.Remove("Code");
or
DataTable dt= new DataView(leaveTypesPerPersonnel).ToTable(false,"ID");
You should be able to run a quick LINQ statement against the data table.
var results = (from item in leaveTypesPerPersonnel
select item.ID);
This will give you an IEnumerable if I remember correctly. It's not a DataTable, but might provide a solution to your problem as well.
Here is a try on how to search and convert the result to DataTable
var dataTable = leaveTypesPerPersonnel.Rows.Cast<DataRow>().ToList().Where(x=> x["ID"] == 21).CopyToDataTable().DefaultView.ToTable(false, "ID");
Or
var dataTable = leaveTypesPerPersonnel.Select("ID = 21").CopyToDataTable().DefaultView.ToTable(false, "ID");
Or
var dataTable = leaveTypesPerPersonnel.Rows.Cast<DataRow>().ToList().CopyToDataTable().DefaultView.ToTable(false, "ID");

How to use Not In datatable.select

I have a DataTable (Ado.Net) with column 'Status'. This column holds the values (in each records)
['Red','Green','Blue','Yellow','White','OtherColors']
I want to select all the rows which status value not Red,Green,Blue
What the kind of filter expression to use to select data with my proposed criteria. So i want to achive some thing like we used in sql query ( WHERE Status NOT IN ('Red','Green','Blue')
NB:This project is running .NET 2.0 i cant use linq
I have tested it, it works as desired:
DataRow[] filtered = tblStatus.Select("Status NOT IN ('Red','Green','Blue')");
The resulting DataRow[] contains only DataRows with OtherColors, Yellow and White.
If you could use LINQ i'd prefer that:
string[] excludeStatus = {"Red","Green","Blue"};
var filteredRows = tblStatus.AsEnumerable()
.Where(row => !excludeStatus.Contains(row.Field<string>("Status")));
Without Linq you can use the rowfilter of a DataView like this
public DataTable GetFilteredData(DataTable table, string[] filterValues)
{
var dv = new DataView(table);
var filter = string.join("','", filterValues);
dv.RowFilter = "Status NOT IN ('" + filter + "')";
return dv.ToTable();
}
Supposing your datatable is part of a typed dataset you can use Linq to datasets, from which you could something like:
var records =
from record in datatable
where !record.Status.Contains('Red','Green','Blue')
select record;
Even if you don't have a typed dataset Linq to datasets is your answer. You would need to some casting, but not to difficult.

Update multiple rows in datatable without loop

I have two datatable with conditions in application and want some processing for multiple rows to update column value.
For example:
I have datatable1 with 10000 rows. I want to filter rows by datatable.select("condition") and as per condition, I want to update row values.
If for any condition, I found 20 rows from datatable. I want to update those 20 records in one shot. Not in any loop. I have datarow array for those values to update in datable.
You can try out the following linq,
DataTable recTable = new DataTable();
// do stuff to populate table
recTable.Select(string.Format("[code] = '{0}'", someName)).ToList<DataRow>().ForEach(r => r["Color"] = colorValue);
You can substitute your columns and values here...
To Update Row With Multiple Condition use This
datatable.Select(string.Format("[lineNo]='{0}' and [Position]>='{1}' ", lineNo, Position)).ToList<DataRow>().ForEach(r => r["Linetext"] ="Sample Text" );
If you want to default a column value with abc use Expression, then you could use the below code.
dt.Columns.Add("ColumnName").Expression = "'abc'";
In case if you need to pass the value dynamically using a variable, you could use the below code.
string str = "abc";
dt.Columns.Add("ColumnName").Expression = "'" + str + "'";

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

Categories