I have DataTable containing three columns, Name, Date and DialedNumber. I want to get rows on the basis of DialedNumber column having phone number like 03001234567 ...
I am filing datatable with an method return type is datatable.
{
DataTable dt = filldata();
}
Problem is how to use select statement to get rows having number 03001234567 or some other telephone number ?
Try this Suppose you have a variable **string str** which is having that telephone number which you want to get from that data table then you can use this
{
DataTable dt = filldata();
DataRow[] resut = dt.Select("DialedNumber ='" + str + "'");
}
It will return you those rows having same telephone number in column DialedNumber.
If you want to filter from the start, not getting all table rows every time, you should adjust your SQL statement:
SELECT * FROM Table WHERE DialedNumber = #dialedNumber
and in C# use SqlCommand.Parameters.AddWithValue(...) to add the #dialedNumber parameter to the query.
Try to use Linq to DataTable like this
var results = from myRow in dt.AsEnumerable()
where myRow.Field<String>("DialedNumber") == "03001234567"
select myRow;
You can use Linq to DataSet:
string number = "03001234567";
var rows = dt.AsEnumerable()
.Where(r => r.Field<string>("DialedNumber").Contains(number));
You even can project rows into strongly typed objects:
var people = from r in dt.AsEnumerable()
where r.Field<string>("DialedNumber").Contains(number)
select new {
Name = r.Field<string>("Name"),
Date = r.Field<DateTime>("Date"),
DialedNumber = r.Field<string>("DialedNumber")
};
Note: if you want to check exact match of dialed number, then instead of Contains(number) (which is equivalent of LIKE) use == number.
Try like this
private void GetRowsByFilter()
{
DataTable table = DataSet1.Tables["Table1"];
// Presuming the DataTable has a column named Date.
string expression;
expression = "DialedNumber ='03001234567 '";
DataRow[] foundRows;
// Use the Select method to find all rows matching the filter.
foundRows = table.Select(expression);
// Print column 0 of each returned row.
for(int i = 0; i < foundRows.Length; i ++)
{
Console.WriteLine(foundRows[i][0]);
}
}
DataTable.Select Method
Related
I am getting a datatable object of a certain type from strongly typed dataset, now I want to find out if one of the column "Title" has certain string in it.
I am trying this, is there any better way ?
FruitDataAccess fda = new FruitDataAccess();
FruitDataTable fdt = cda.GetFriuts(fruitCrateID);
DataTable dt = fdt.CopyToDataTable();
var row = dt.Rows.Cast<DataRow>().Any(r => r.ItemArray.Any(c => c.ToString().Contains("whatever")));
Use LINQ TO DataSet/DataTable like:
var search = dt.AsEnumerable()
.FirstOrDefault(r=> r.Field<string>("Title") == "your string");
if(search != null)
{
//found
}
You can also find rows with your condition like:
DataRow[] foundRows;
foundRows = dt.Select("Title Like '%your string%'"); //similar to Contains
See: How to: Locate a Specific Row in a DataTable
How do filter a empty String in DataTable?
I need to filter a column (say Customer Name where the name is string.Empty)
I tried this but i cant get into right way..
I need to filter the DataView through DataView.RowFilter.. so how to give filter string for string.Empty..
Any idea on this?
To filter a dataTable-
dt.Select("customer_name = ''");
To Filter datatview-
dv.RowFilter = "customer_name = ''";
Use Select method:
DataRow[] foundRows = dt.Select("MyColumn = ''");
You can use Select method for DataTable:
//selects all customers which name is empty
var rows = dtData.Select("CustomerName = ''");
See the code below, might be a help. I am answering as the question has a tag RowFilters
private void GetRowsByFilter()
{
DataTable table = DataSet1.Tables["YourTable"];
// Presuming the DataTable has a column named Date.
string expression = "Column_name = ''";
// Sort descending by column named CompanyName.
string sortOrder = "ColumnName DESC";
DataRow[] foundRows;
// Use the Select method to find all rows matching the filter.
foundRows = table.Select(expression, sortOrder);
// Print column 0 of each returned row.
for(int i = 0; i < foundRows.Length; i ++)
{
Console.WriteLine(foundRows[i][0]);
}
}
Try below code:
DataTable dt=new DataTable();
DataRow dr;
dr=dt.NewRow();
if(dr["CustomerName"]==null)
{
put some code here.........
}
i Hope This code will help 4 u
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
I am trying to figure out how to append a column to Linq query results based on the max value of the query. Essentially, I want to create an EnumerableRowCollection of DataRows that would include a max value record with the same value for each record. So if i have a hundred records returned through the query, I want to next calculate the max value of one of the fields, then append that max value to the original query table:
DataTable dt = new DataTable();
dt = myDataSet.myDataTable;
EnumerableRowCollection<DataRow> qrySelectRecords =
(from d in dt.AsEnumerable()
where d.Field<DateTime>("readingDate") >= startDate && g.Field<DateTime>("readingDate") <= endDate
select d);
Here's where I need help:
double maxValue = qrySelectRecords.Field<double>("field1").Max();
foreach (DataRow dr in qrySelectRecords)
{
qrySelectRecords.Column.Append(maxValue)
}
Couple points, first: new DataTable() is redundant; you're instantiating a rather expensive object that will never be used because you're overwriting the reference in the very next line. You should consider removing the initialization and then joining the declaration and the actual assignment on one line.
Getting to the real question. DataRows cannot have columns added to them directly; you have to add the column to the entire DataTable containing those rows. Once that's done, just set the value. As long as you don't need the operation translated into an external query language like SQL, you can inline this operation using a monadic extension method:
DataTable dt = myDataSet.myDataTable;
dt.Columns.Add("MaxField1");
EnumerableRowCollection<DataRow> qrySelectRecords =
(from d in dt.Rows().AsEnumerable().OfType<DataRow>()
where d.Field<DateTime>("readingDate") >= startDate
&& d.Field<DateTime>("readingDate") <= endDate
let m = dt.AsEnumerable().Max(dr=>dr.Field<double>("field1"))
select d.WithColumnSet("MaxField1", m));
...
public static DataRow WithColumnSet(this DataRow input, string columnName, object value)
{
input[columnName] = value;
return input;
}
I have a datatable with a bunch of rows in it, the first column is an Int32 and I want to perform a simple select like:
select * from MyDataTable where column1 = 234
Try this to get result as row array :
DataRow[] rows = myDataTable.Select("column1 = 234");
Or this to get dataview :
DataView myDataView = myDataTable.DefaultView;
myDataView.RowFilter = "column1 = 234";
var result = from row in table.AsEnumerable()
where row[0].Equals(42)
select row;
Or
var result = table.AsEnumerable().Where(row => row[0].Equals(42));
if you're talking of a System.Data.DataTable, you can use datatable.Rows.Find for searching a row by primaryKey, or datatable.Select for obtaining a array of rows that satisfy your condition.
// By DataTable's primary key
datatable.Rows.Find(234);
// By compound primary key
datatable.Rows.Find(234, 1, 4);
// by Select
datatable.Select("column1=234");
// by Compound Select
datatable.Select("column1=234 AND column2=1");