How to make C# DataTable filter - c#

my datatable;
dtData
ID | ID2
--------
1 | 2
1 | 3
dtData.Select("ID = 1"); one more rows;
i want row "ID = 1 And ID2 = 3" how to make ?

Do you mean like this?:
dtData.Select("ID=1 AND ID2=3");

Okay, here is how I do such things...
GridFieldDAO dao = new GridFieldDAO();
//Load My DataTable
DataTable dt = dao.getDT();
//Get My rows based off selection criteria
DataRow[] drs = dt.Select("(detailID = 1) AND (detailTypeID = 2)");
//make a new "results" datatable via clone to keep structure
DataTable dt2 = dt.Clone();
//Import the Rows
foreach (DataRow d in drs)
{
dt2.ImportRow(d);
}
//Bind to my new DataTable and it will only show rows based off selection
//criteria
myGrid.DataSource = dt2;
myGrid.DataBind();
Notice in my Select() I put the criteria in Parens between AND and OR
Hope this helps!
Mike V

Better use this :
GridFieldDAO dao = new GridFieldDAO();
//Load My DataTable
DataTable dt = dao.getDT();
//Get My rows based off selection criteria and copy them directly to datatable
DataTable dt2 = dt.Select("(detailID = 1) AND (detailTypeID = 2)").CopyToDataTable();

DataTable dt2 = dt.Select("ID = 1").CopyToDataTable;
make sure dt has rows in it

Here you can copy your contents to another DataTable by using CopyToDataTable method of Linq while selecting the specific rows by filtering.
DataTable dt2 = dt.Select("state = 'FL' ").CopyToDataTable;

Great example and very helpful. Wanted to add one thing - if you need to select on a string use something like:
DataTable dt2 = dt.Select("state = 'FL' ");

Related

How to perform multiplication on two column for datagrid view and assigning it in third column?

Here is my code, I am trying to display multiplication of Rate * Supply column values and assigning it to the Amount column in data grid view :
try
{
Query = "Select id,Code,Description,Rate,Cust_Id,Supply,Empty,Amount,Received from Items ";
adap = new SQLiteDataAdapter(Query, GlobalVars.conn);
ds = new DataSet();
adap.Fill(ds, "Items");
dtgVOuchers.DataSource = ds.Tables[0];
ds.Tables[0].Columns["Amount"].DefaultValue = (ds.Tables[0].Columns["Rate"].DefaultValue) * (ds.Tables[0].Columns["Supply"].DefaultValue); //error
//dtgVOuchers.Rows.Clear();
ds.Tables[0].Clear();
dtgVOuchers.Refresh();
}
Does anyone know how I can accomplish this functionality in data grid view ? . .Please help me to correct this code. Thanks
just use the query
Select id,Code,Description,Rate,Cust_Id,Supply,Empty,isnull(Rate,0)*isnull(Supply,0) as [Amount],Received from Items
DataTable myDataTable = new DataTable();
DataColumn quantityColumn = new DataColumn("Quantity");
DataColumn rateColumn = new DataColumn("Rate");
DataColumn priceColumn = new DataColumn ("Price");
quantityColumn.DataType = typeof(int);
rateColumn.DataType = typeof(int);
myDataTable.Columns.Add(quantityColumn);
myDataTable.Columns.Add(rateColumn);
myDataTable.Columns.Add(priceColumn);
//Set the Expression here
priceColumn.Expression = "Quantity * Rate";
foreach (DataGridViewRow row in dtgVOuchers.Rows)
{
row.Cells[dtgVOuchers.Columns["Amount"].Index].Value = (Convert.ToDouble(row.Cells[dtgVOuchers.Columns["Rate"].Index].Value) * Convert.ToDouble(row.Cells[dtgVOuchers.Columns["Supply"].Index].Value));
}
Use the below code..run a loop to update the Amount column in all rows
Note : Though this method is not preferred as it effects performance.So do this calculation in the sql query.I dont understand the reason behind not doing the munltiplication in SQL query..
foreach (DataRow row in ds.Tables[0].Rows)
{
row["Amount"]= Convert.ToDecimal(row["Rate"])* Convert.ToDecimal(row["Supply"]);
ds.Tables[0].AcceptChanges();
}
dtgVOuchers.DataSource = ds.Tables[0];
dtgVOuchers.Refresh();

two datatable adding

I have two datatables.
1st table-----> DataTable _dtMain = new COrder().GetDetails();
2nd table-----> DataTable _dtSub = new CGrid().GetSubDetails();
I want to add the above two tables. I am using _dtMain.Merge(_dtSub );
But it will append _dtSub table to _dtMain table. I want datatable to add second table to first table in column wise (that means after first table last column)
Don't think there any built-in method for the thing you want to achieve.
I think you need to make your own implementation for that stuff, like for example an extension method
public static DataTable Aggregate(this DataTable dt1, DataTable dt2)
{
var aggregator = new DataTable();
//add columns from dt1 and dt2
//add rows from dt1 dt2
}
or, you can do a complete Outer Join on both tables, like descrived in this article.
After a lot of research , i find out the answer for my question that i posted before. Here is the code for combing 2 datatable & the data inside it.
public DataTable CombineTable(DataTable _dtGridDetails, DataTable _dtSubGridDetails)
{
//first create the datatable columns
DataSet mydataSet = new DataSet();
mydataSet.Tables.Add(" ");
DataTable myDataTable = mydataSet.Tables[0];
//add left table columns
DataColumn[] dcLeftTableColumns = new DataColumn[_dtGridDetails.Columns.Count];
_dtGridDetails.Columns.CopyTo(dcLeftTableColumns, 0);
foreach (DataColumn LeftTableColumn in dcLeftTableColumns)
{
if (!myDataTable.Columns.Contains(LeftTableColumn.ToString()))
myDataTable.Columns.Add(LeftTableColumn.ToString());
}
//now add right table columns
DataColumn[] dcRightTableColumns = new DataColumn[_dtSubGridDetails.Columns.Count];
_dtSubGridDetails.Columns.CopyTo(dcRightTableColumns, 0);
foreach (DataColumn RightTableColumn in dcRightTableColumns)
{
if (!myDataTable.Columns.Contains(RightTableColumn.ToString()))
{
// if (RightTableColumn.ToString() != RightPrimaryColumn)
myDataTable.Columns.Add(RightTableColumn.ToString());
}
}
//add left-table data to mytable
foreach (DataRow LeftTableDataRows in _dtGridDetails.Rows)
{
myDataTable.ImportRow(LeftTableDataRows);
}
for (int nIndex = 0; nIndex <= myDataTable.Rows.Count-1; nIndex++)
{
if (nIndex == _dtSubGridDetails.Rows.Count)
break;
myDataTable.Rows[nIndex][columnindex] = _dtSubGridDetails.Rows[nIndex][columnindex];
}
return myDataTable;
}

Sorting rows in a data table

We have two columns in a DataTable, like so:
COL1 COL2
Abc 5
Def 8
Ghi 3
We're trying to sort this datatable based on COL2 in decreasing order.
COL1 COL2
ghi 8
abc 4
def 3
jkl 1
We tried this:
ft.DefaultView.Sort = "COL2 desc";
ft = ft.DefaultView.ToTable(true);
but, without using a DataView, we want to sort the DataTable itself, not the DataView.
I'm afraid you can't easily do an in-place sort of a DataTable like it sounds like you want to do.
What you can do is create a new DataTable from a DataView that you create from your original DataTable. Apply whatever sorts and/or filters you want on the DataView and then create a new DataTable from the DataView using the DataView.ToTable method:
DataView dv = ft.DefaultView;
dv.Sort = "occr desc";
DataTable sortedDT = dv.ToTable();
This will help you...
DataTable dt = new DataTable();
dt.DefaultView.Sort = "Column_name desc";
dt = dt.DefaultView.ToTable();
Its Simple Use .Select function.
DataRow[] foundRows=table.Select("Date = '1/31/1979' or OrderID = 2", "CompanyName ASC");
DataTable dt = foundRows.CopyToDataTable();
And it's done......Happy Coding
Maybe the following can help:
DataRow[] dataRows = table.Select().OrderBy(u => u["EmailId"]).ToArray();
Here, you can use other Lambda expression queries too.
Or, if you can use a DataGridView, you could just call Sort(column, direction):
namespace Sorter
{
using System;
using System.ComponentModel;
using System.Windows.Forms;
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
this.dataGridView1.Rows.Add("Abc", 5);
this.dataGridView1.Rows.Add("Def", 8);
this.dataGridView1.Rows.Add("Ghi", 3);
this.dataGridView1.Sort(this.dataGridView1.Columns[1],
ListSortDirection.Ascending);
}
}
}
Which would give you the desired result:
Did you try using the Select(filterExpression, sortOrder) method on DataTable? See here for an example. Note this method will not sort the data table in place, if that is what you are looking for, but it will return a sorted array of rows without using a data view.
table.DefaultView.Sort = "[occr] DESC";
Use LINQ - The beauty of C#
DataTable newDataTable = baseTable.AsEnumerable()
.OrderBy(r=> r.Field<int>("ColumnName"))
.CopyToDataTable();
There is 2 way for sort data
1) sorting just data and fill into grid:
DataGridView datagridview1 = new DataGridView(); // for show data
DataTable dt1 = new DataTable(); // have data
DataTable dt2 = new DataTable(); // temp data table
DataRow[] dra = dt1.Select("", "ID DESC");
if (dra.Length > 0)
dt2 = dra.CopyToDataTable();
datagridview1.DataSource = dt2;
2) sort default view that is like of sort with grid column header:
DataGridView datagridview1 = new DataGridView(); // for show data
DataTable dt1 = new DataTable(); // have data
dt1.DefaultView.Sort = "ID DESC";
datagridview1.DataSource = dt1;
It turns out there is a special case where this can be achieved. The trick is when building the DataTable, collect all the rows in a list, sort them, then add them. This case just came up here.
//Hope This will help you..
DataTable table = new DataTable();
//DataRow[] rowArray = dataTable.Select();
table = dataTable.Clone();
for (int i = dataTable.Rows.Count - 1; i >= 0; i--)
{
table.ImportRow(dataTable.Rows[i]);
}
return table;
TL;DR
use tableObject.Select(queryExpression, sortOrderExpression) to select data in sorted manner
Complete example
Complete working example - can be tested in a console application:
using System;
using System.Data;
namespace A
{
class Program
{
static void Main(string[] args)
{
DataTable table = new DataTable("Orders");
table.Columns.Add("OrderID", typeof(Int32));
table.Columns.Add("OrderQuantity", typeof(Int32));
table.Columns.Add("CompanyName", typeof(string));
table.Columns.Add("Date", typeof(DateTime));
DataRow newRow = table.NewRow();
newRow["OrderID"] = 1;
newRow["OrderQuantity"] = 3;
newRow["CompanyName"] = "NewCompanyName";
newRow["Date"] = "1979, 1, 31";
// Add the row to the rows collection.
table.Rows.Add(newRow);
DataRow newRow2 = table.NewRow();
newRow2["OrderID"] = 2;
newRow2["OrderQuantity"] = 2;
newRow2["CompanyName"] = "NewCompanyName1";
table.Rows.Add(newRow2);
DataRow newRow3 = table.NewRow();
newRow3["OrderID"] = 3;
newRow3["OrderQuantity"] = 2;
newRow3["CompanyName"] = "NewCompanyName2";
table.Rows.Add(newRow3);
DataRow[] foundRows;
Console.WriteLine("Original table's CompanyNames");
Console.WriteLine("************************************");
foundRows = table.Select();
// Print column 0 of each returned row.
for (int i = 0; i < foundRows.Length; i++)
Console.WriteLine(foundRows[i][2]);
// Presuming the DataTable has a column named Date.
string expression = "Date = '1/31/1979' or OrderID = 2";
// string expression = "OrderQuantity = 2 and OrderID = 2";
// Sort descending by column named CompanyName.
string sortOrder = "CompanyName ASC";
Console.WriteLine("\nCompanyNames data for Date = '1/31/1979' or OrderID = 2, sorted CompanyName ASC");
Console.WriteLine("************************************");
// 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][2]);
Console.ReadKey();
}
}
}
Output
try this:
DataTable DT = new DataTable();
DataTable sortedDT = DT;
sortedDT.Clear();
foreach (DataRow row in DT.Select("", "DiffTotal desc"))
{
sortedDT.NewRow();
sortedDT.Rows.Add(row);
}
DT = sortedDT;
Yes the above answers describing the corect way to sort datatable
DataView dv = ft.DefaultView;
dv.Sort = "occr desc";
DataTable sortedDT = dv.ToTable();
But in addition to this, to select particular row in it you can use LINQ and try following
var Temp = MyDataSet.Tables[0].AsEnumerable().Take(1).CopyToDataTable();

dataview rowfilter value to datatable convertion

I want to convert dataview rowfilter value to datatable. I have a dataset with value. Now i was filter the value using dataview. Now i want to convert dataview filter values to datatable.please help me to copy it........
My partial code is here:
DataSet5TableAdapters.sp_getallempleaveTableAdapter TA = new DataSet5TableAdapters.sp_getallempleaveTableAdapter();
DataSet5.sp_getallempleaveDataTable DS = TA.GetData();
if (DS.Rows.Count > 0)
{
DataView datavw = new DataView();
datavw = DS.DefaultView;
datavw.RowFilter = "fldempid='" + txtempid.Text + "' and fldempname='" + txtempname.Text + "'";
if (datavw.Count > 0)
{
DT = datavw.Table; // i want to copy dataview row filter value to datatable
}
}
please help me...
You can use
if (datavw.Count > 0)
{
DT = datavw.ToTable(); // This will copy dataview's RowFilterd values to datatable
}
You can use DateView.ToTable() for converting the filtered dataview in to a datatable.
DataTable DTb = new DataTable();
DTb = SortView.ToTable();
The answer does not work for my situation because I have columns with expressions. DataView.ToTable() will only copy the values, not the expressions.
First I tried this:
//clone the source table
DataTable filtered = dt.Clone();
//fill the clone with the filtered rows
foreach (DataRowView drv in dt.DefaultView)
{
filtered.Rows.Add(drv.Row.ItemArray);
}
dt = filtered;
but that solution was very slow, even for just 1000 rows.
The solution that worked for me is:
//create a DataTable from the filtered DataView
DataTable filtered = dt.DefaultView.ToTable();
//loop through the columns of the source table and copy the expression to the new table
foreach (DataColumn dc in dt.Columns)
{
if (dc.Expression != "")
{
filtered.Columns[dc.ColumnName].Expression = dc.Expression;
}
}
dt = filtered;
The below code is for Row filter from Dataview and the result converted in DataTable
itemCondView.RowFilter = "DeliveryNumber = '1001'";
dataSet = new DataSet();
dataSet.Tables.Add(itemCondView.ToTable());

Simple way to convert datarow array to datatable

I want to convert a DataRow array into DataTable ... What is the simplest way to do this?
For .Net Framework 3.5+
DataTable dt = new DataTable();
DataRow[] dr = dt.Select("Your string");
DataTable dt1 = dr.CopyToDataTable();
But if there is no rows in the array, it can cause the errors such as The source contains no DataRows. Therefore, if you decide to use this method CopyToDataTable(), you should check the array to know it has datarows or not.
if (dr.Length > 0)
DataTable dt1 = dr.CopyToDataTable();
Reference available at MSDN:
DataTableExtensions.CopyToDataTable Method (IEnumerable)
Why not iterate through your DataRow array and add (using DataRow.ImportRow, if necessary, to get a copy of the DataRow), something like:
foreach (DataRow row in rowArray) {
dataTable.ImportRow(row);
}
Make sure your dataTable has the same schema as the DataRows in your DataRow array.
DataTable dt = new DataTable();
DataRow[] dr = (DataTable)dsData.Tables[0].Select("Some Criteria");
dt.Rows.Add(dr);
Another way is to use a DataView
// Create a DataTable
DataTable table = new DataTable()
...
// Filter and Sort expressions
string expression = "[Birth Year] >= 1983";
string sortOrder = "[Birth Year] ASC";
// Create a DataView using the table as its source and the filter and sort expressions
DataView dv = new DataView(table, expression, sortOrder, DataViewRowState.CurrentRows);
// Convert the DataView to a DataTable
DataTable new_table = dv.ToTable("NewTableName");
Simple way is:
// dtData is DataTable that contain data
DataTable dt = dtData.Select("Condition=1").CopyToDataTable();
// or existing typed DataTable dt
dt.Merge(dtData.Select("Condition=1").CopyToDataTable());
DataTable Assetdaterow =
(
from s in dtResourceTable.AsEnumerable()
where s.Field<DateTime>("Date") == Convert.ToDateTime(AssetDate)
select s
).CopyToDataTable();
DataTable dt = myDataRowCollection.CopyToDataTable<DataRow>();
DataTable dt = new DataTable();
foreach (DataRow dr in drResults)
{
dt.ImportRow(dr);
}
.Net 3.5+ added DataTableExtensions, use DataTableExtensions.CopyToDataTable Method
For datarow array just use .CopyToDataTable() and it will return datatable.
For single datarow use
new DataRow[] { myDataRow }.CopyToDataTable()
You could use System.Linq like this:
if (dataRows != null && dataRows.Length > 0)
{
dataTable = dataRows.AsEnumerable().CopyToDataTable();
}
Here is the solution. It should work fine.
DataTable dt = new DataTable();
dt = dsData.Tables[0].Clone();
DataRows[] drResults = dsData.Tables[0].Select("ColName = 'criteria');
foreach(DataRow dr in drResults)
{
object[] row = dr.ItemArray;
dt.Rows.Add(row);
}
Incase anyone needs it in VB.NET:
Dim dataRow as DataRow
Dim yourNewDataTable as new datatable
For Each dataRow In yourArray
yourNewDataTable.ImportRow(dataRow)
Next
You need to clone the structure of Data table first then import rows using for loop
DataTable dataTable =dtExisting.Clone();
foreach (DataRow row in rowArray) {
dataTable.ImportRow(row);
}
DataTable dataTable = new DataTable();
dataTable = OldDataTable.Tables[0].Clone();
foreach(DataRow dr in RowData.Tables[0].Rows)
{
DataRow AddNewRow = dataTable.AddNewRow();
AddNewRow.ItemArray = dr.ItemArray;
dataTable.Rows.Add(AddNewRow);
}

Categories