Using Aggregate functions in DataView filters - c#

i have a DataTable that has a column ("Profit"). What i want is to get the Sum of all the values in this table. I tried to do this in the following manner...
DataTable dsTemp = new DataTable();
dsTemp.Columns.Add("Profit");
DataRow dr = null;
dr = dsTemp.NewRow();
dr["Profit"] = 100;
dsTemp.Rows.Add(dr);
dr = dsTemp.NewRow();
dr["Profit"] = 200;
dsTemp.Rows.Add(dr);
DataView dvTotal = dsTemp.DefaultView;
dvTotal.RowFilter = " SUM ( Profit ) ";
DataTable dt = dvTotal.ToTable();
But i get an error while applying the filter...
how can i get the Sum of the Profit column in a variable
thank you...

Set the datacolumn to a numeric type (int, decimal, whatever):
DataColumn col = new DataColumn("Profit", typeof(int));
dsTemp.Columns.Add(col);
Use Compute:
int total = dsTemp.Compute("Sum(Profit)", "");
Note that aggregation is not a type of filter, which is the main problem with the approach you are tyring.

I used the DataTable's Compute method as suggested, and it works fine. I apply the same filtering as I use for the DataView (which is used to display the sorted and filtered data in the data grid) together with an aggregate function.
string SingleVocheridSale ="1";
DataView view = new DataView(dt);
view.RowFilter = string.Format("VOCHID='" + SingleVocheridSale + "'");
dataGridview1.DataSource = view;
object sumObject;
sumObject = dt.Compute("Sum(NETAMT)", view.RowFilter);
lable1.Text = sumObject.ToString();

Related

C# dataview to datatable becomes null

I have a DataTable that I make a DataView with. In the Dataview, I filter and sort the info from the first DataTable. Then I tried to make a new DataTable out of the DataView where I sorted and filtered the content.
Everything seems to work alright but the new DataTable is null, so I lost the content from the original DataTable and the rest of the function does not work anymore. Also, I am getting an Unreachable Code warning in File B # System.Data.DataTable dt480 = dv.ToTable();
I'll keep trying to solve this but I'd like to see if I am way off, or on the right track. Thanks in advance.
I have two files where the code is stored.
File A:
static public void ElecOneLine1(System.Data.DataView dv)
{
string Path = Commands.LoadFile();
System.Data.DataTable table = Commands.ReadExcelToTable(Path);
Commands.ElecDv480V(table);
//Commands.OneLineDt(dv);
Commands.InsertElec1LineBlockscd();
Commands.DrawOneLineBuscd("OneLineBackground", 35.5478, 23.3750, 0, table.Rows[0]);
for (int i = 1; i < 8; i++)
{
Commands.DrawOneLineItem("" + table.Rows[1 + i][0], 4 + ((double)i * 3), 12.6835, 0, table.Rows[0], i + 1);
}
}
File B (called "Commands"):
public static DataView ElecDv480V(System.Data.DataTable dt)
{
System.Data.DataView dv = new DataView(dt);
dv.RowFilter = "F1 = '480V'";
dv.Sort = "F2 ASC, F3 ASC";
return dv;
System.Data.DataTable dt480 = dv.ToTable();
}
return should be the last statement.The return statement terminates execution of the method in which it appears
public static DataView ElecDv480V(System.Data.DataTable dt)
{
System.Data.DataView dv = new DataView(dt);
dv.RowFilter = "F1 = '480V'";
dv.Sort = "F2 ASC, F3 ASC";
System.Data.DataTable dt480 = dv.ToTable();
return dv;
}
Also,You are returning a dataview so you need to have a variable at receiving end also which you are missing.Beside what is the use of setting values for dt480

How to display specific row of data based on a column value

From this code I am trying to only display data rows that contain the fields "DBY" in the Station_From_Code column and "MAT" in the Station_To_Column. This will then be printed onto a HTML page. These fields are definitely in the datatable but when I run this cod the table is empty. I am not used to working with data tables in C# so apologies for the poor coding.
dynamic schedluedContent = JsonConvert.DeserializeObject(scheduledJson);
JArray items2 = new JArray();
foreach (JObject stops in schedluedContent.stops)
{
DataTable dt = new DataTable();
DataRow dr;
dr = dt.NewRow();
dr["From_Station_Code"] = stops["station_code"];
dr["To_Station_Code"] = stops["station_code"];
dt.Rows.Add(dr);
DataRow[] result = dt.Select("From_Station_Code = 'DBY' AND To_Station_Code = 'MAT'");
dt.Rows.Add(result);
GridViewTrainTimes.DataSource = dt;
GridViewTrainTimes.DataBind();
}
It's a long time I have not seen this style of code for working with database tables! EntityFramework comes to change and surely ease the way of working with database and prevent different risks of using SQL commands inside the code.
If you use EF, your code will become something like bellow:
var rows = myDBContext.MyTable.Where(x=>x.From_Station_Code == "DBY" && x.To_Station_Code == "MAT");
GridViewTrainTimes.DataSource = rows;
You can use find match rows and add in new datatable, that contains only your match rows data then you can bind this dt to gridview.
DataTable dt = new Datatable(); // Lets this datatable have data;
Datatable dt2 = new Datatable(); // Copy all matching rows
foreach (DataRow dr in dt.Rows)
{
if (dr["From_Station_Code"].ToString() == "DBY" && dr["To_Station_Code"].ToString() == "MAT")
{
dt2.Rows.Add(dr);
}
}
GridViewTrainTimes.DataSource = dt;
GridViewTrainTimes.DataBind();

How do I search data in from datatable based on user input

I have created one datatable:
DataTable dt=new DataTable();
dt.Columns.Add("Country", typeof(string))
dt.Columns.Add("place", typeof(string))
dt.Columns.Add("Price", typeof(string))
dt.Columns.Add("Desc", typeof(string))
and I have inserted some data in this datatable:
DataRow dtrow = dt.NewRow(); // Create New Row
dtrow["Country"] = "India"; //Bind Data to Columns
dtrow["place"] = "wizag";
dtrow["Price"] = "7520";
dtrow["Desc"] = "Anywhere";
dt.Rows.Add(dtrow);
dtrow = dt.NewRow(); // Create New Row
dtrow["Country"] = "India"; //Bind Data to Columns
dtrow["place"] = "Goa";
dtrow["price"] = "4500";
dtrow["Desc"] = "Anything";
dt.Rows.Add(dtrow);
I have bind this datatable with my grid view. I have also added one textbox and one search button in mmy aspx page. My requirement is that I want to search data based on user input e.g like 4500 or wizag, and if country name is the same I want to show it in one row
How can I do this?
I would use a DataView in this case
DataView dv = new DataView(dt);
dv.RowFilter = "price = 4500 AND Country = 'India'";
GridView.DataSource = dv.ToTable();
GridView.DataBind();

How to bind DataRow to the GridView?

I have one datatable which has four or five columns. I dont know exactly the columns name and its count. But I want to bind the first row of the datatable into the GridView. How to do this? I need all your suggestions please.
Linq should be helpful here to get first item.
var Temp = dt.AsEnumerable().Take(1).CopyToDataTable();
use the filter in the datatable :
dt.Select("ID = 1");
you can try like this..
dt = new DataTable();
dt_Property.Columns.Add("Field1");
int i = 0;
DataRow row = null;
foreach (DataRow r in ds.Tables[0].Rows)
{
row = dt.NewRow();
row["Field1"] = ds.Tables[0].Rows[i][1];
dt_Property.Rows.Add(row);
i = i + 1;
}
dataGridView1.DataSource = dt;

Perform Aggregate function of DataTable

I have to perform the aggregate function on the DataTable like Datatable.Compute but compute return the object i want to perform the aggregate function on the datatable and get the datarow .
_summaryTable.Compute("min(FareAdult)", whereClause
+ "AirlineDisplayName='"
+ Convert.ToString(airline["AirlineDisplayName"])
+ "' and ( Stops=0) ");
but above code will only return the min(FareAdult) but i want to select the two column based on the above condition from datatable.
How can i do it through Linq
I have to select min(FareAdult) and the TotelPrice value of same row
use Select instead compute
_summaryTable.Select("FilterationExpression");
DataRow[] dr = _summaryTable.Select("min(FareAdult),AirlineDisplayName='" + Convert.ToString(airline["AirlineDisplayName"]) + "' and ( Stops=0) ");
Here is a LINQ method. This is pseudocode since I don't know the typing of your row, and I haven't been able to test it, but the idea is the same. Use LINQ to select the rows that match your criteria, order by the FareAdult and then select the first (minimum).
var minResult = (from row in _summaryTable.Rows
where row.AirlineDisplayName == airline["AirlineDisplayName"] && row.Stops == 0
orderby row.FareAdult
select row).FirstOrDefault();
private void CalcColumns()
{
DataTable table = new DataTable ();
//enter code here
// Create the first column.
DataColumn priceColumn = new DataColumn();
priceColumn.DataType = System.Type.GetType("System.Decimal");
priceColumn.ColumnName = "price";
priceColumn.DefaultValue = 50;
// Create the second, calculated, column.
DataColumn taxColumn = new DataColumn();
taxColumn.DataType = System.Type.GetType("System.Decimal");
taxColumn.ColumnName = "tax";
taxColumn.Expression = "price * 0.0862";
// Create third column.
DataColumn totalColumn = new DataColumn();
totalColumn.DataType = System.Type.GetType("System.Decimal");
totalColumn.ColumnName = "total";
totalColumn.Expression = "price + tax";
// Add columns to DataTable.
table.Columns.Add(priceColumn);
table.Columns.Add(taxColumn);
table.Columns.Add(totalColumn);
DataRow row = table.NewRow();
table.Rows.Add(row);
DataView view = new DataView(table);
dataGrid1.DataSource = view;
}

Categories

Resources