MVC C# - DataTable in DataRows with Condition - c#

I have the following DataTable records :-
I want to display the Rows for which HeaderPrintOrder Column don't have 0 as value. And in PDF Cell I have to print FieldName : Amount by iterating to the records with above given condition.
I am trying the below code, gives me error Cannot interpret token '!'. What is correct way to do this?
var datatable = new DataTable();
datatable.Load(reader);
DataRow[] HeadingFields = datatable.Select("HeaderPrintOrder != 0");
foreach (var item in HeadingFields)
{
cellHead = new PdfPCell(new Phrase(HeadingFields[item]["FieldName"].ToString() + " : " + HeadingFields[item]["Amount"].ToString(), fntTableFont));
cellHead.Colspan = 3;
MainTable.AddCell(cellHead);
}

With LINQ it's easy:
var filtered = datatable.AsEnumerable()
.Where(row => row.Field<int>("HeaderPrintOrder") != 0);
foreach(DataRow row in filtered)
{
// ....
}
With DataTable.Select you have to use <> instead of !=:
DataRow[] HeadingFields = datatable.Select("HeaderPrintOrder <> 0");
<> is supported whereas != is not. You can see that here:
http://msdn.microsoft.com/en-us/library/system.data.datacolumn.expression%28v=vs.110%29.aspx

The != operator is not supported by the RowFilter syntax.
Try:
DataRow[] HeadingFields = datatable.Select("NOT (HeaderPrintOrder = 0)");

Try with Linq:
var HeadingFields= from row in datatable .AsEnumerable()
where row.Field<int>("HeaderPrintOrder") <> (int)(0)
select row;

Related

How to store data table value in another data table with filter

How to store data table value in another data table with filter.
DataTabe dt = objProfitLossDT.Select("AppBalance <= 0");
Is this what you want?
DataTable dt = objProfitLossDT.Select("AppBalance <= 0").CopyToDataTable();
Note that CopyToDataTable throws an exception if there is no row in source. So you should check it:
DataTable dt = objProfitLossDT.Clone(); // Clone is better than assigning null if you need the columns with an empty table
DataRow[] filteredRows = objProfitLossDT.Select("AppBalance <= 0");
if(filteredRows.Length > 0)
dt = objProfitLossDT.Select("AppBalance <= 0").CopyToDataTable();
By the way, you know that you could also use LINQ, which is much more powerful than Select:
var filteredRows = objProfitLossDT.AsEnumerable()
.Where(row => row.Field<int>("AppBalance) <= 0)
.ToArray(); // if you want a DataRow[]

How to get each value from a particular mysql table by using datatable without using a for or foreach loop in c#?

I need to get each value from mysql table by using DataTable without using a loop. Here I have two DataTables, I want to increment dtfilmsngtemp and need to get values, i.e if dtsnglyric have id=2, Then I need to have get id=2 in dtfilmsngtemp, So in general I need to get he same 'id's' from two DataTables. First of all row id is 1 in dtsnglyric and dtfilmsngtemp, But dtsnglyric is incremented to 2, According to my requirement dtfilmsngtemp is also need to become 2. How it is possible?
DataTable dtsnglyric = GetAllsnglyrctmp();
DataTable dtfilmsngtemp = GetAllfilmsngtemp();
foreach (DataRow drow1 in dtsnglyric.Rows)
{
string lyrsct = drow1["lyricist"].ToString();
string sngrs = drow1["singers"].ToString();
foreach (DataRow drow in dtfilmsngtemp.Rows)
{
string lid = drow["lyric_id"].ToString();
string fid = drow["film_id"].ToString();
}
}
Try this
protected void Page_Load(object sender, EventArgs e)
{
// Check
if (!IsPostBack)
{
// Variable
DataTable dt1 = new DataTable();
DataTable dt2 = new DataTable();
DataRow[] dr1 = null;
DataRow[] dr2 = null;
string value1 = string.Empty;
string value2 = string.Empty;
dt1.Columns.Add("A");
dt1.Columns.Add("B");
dt2.Columns.Add("A");
dt2.Columns.Add("B");
// Add to DataTable
for (int i = 0; i < 10; i++)
{
dt1.Rows.Add(i.ToString(), (i + 1).ToString());
dt2.Rows.Add(i.ToString(), (i + 2).ToString());
}
// Find By Select Example i want to take dt1 Column A = 2 and dt2 Column A = 9
dr1 = dt1.Select("A=2"); // Select statement >>> Column = Value
dr2 = dt2.Select("A=9");
// Check & Get B Value
if (dr1 != null && dr1.Length == 1) value1 = dr1[0]["B"] + "";
if (dr2 != null && dr2.Length == 1) value2 = dr2[0]["B"] + "";
Response.Write(value1 + ":" + value2);
}
}
I think you need an inner join operation. Can't you do it in the SQL query? DataTable doesn't support that, but you can do it with LINQ. However, note that it will take O(n^2) time and shouldn't be used for big tables:
var results = from table1 in dtsnglyric.AsEnumerable()
join table2 in dtfilmsngtemp.AsEnumerable() on (int)table1["lyricist"] equals (int)table2["lyric_id"]
select new
{
lyricist= (int)table1["lyricist"],
lyric_id= (int)table2["lyric_id"],
film_id= (int)table2["film_id"],
singers = (int)table1["singers"]
};

if condition to set the DataTextField for a databind

I'm trying to set selectively display certain text using a databind.
the code looks like this..
DataTable oDt;
oDt = Apps.GetAll();
if (oDt.Rows.Count > 0)
{
oDt.Columns.Add("AppName_ID", typeof(string), "App_Name + ' (' + App_ID + ')'");
CmbApps.DataSource = oDt;
CmbApps.DataValueField = "App_ID";
CmbApps.DataTextField = "AppName_ID";
CmbApps.DataBind();
}
The problem is that the first value shows up as: Select (0).. so I'm trying to change the datatextfield when "App_ID" = 0 so that App_ID is NOT displayed, but is in all other values.
Not sure about the syntax, but it will be close to the below.
DataTable dt2 = oDt.Select("(App_ID != 0)").CopyToDataTable();
Using Linq-To-DataTable
DataTable tblFiltered = oDt.AsEnumerable()
.Where(row => row.Field<String>("App_ID") == "1")
.CopyToDataTable();
Or you can use DataView and RowFilter
DataView dataView = oDt.DefaultView;
dataView.RowFilter = "App_ID <> 0";
UPDATE
foreach (DataRow DRow in oDt.Rows)
{
if(DRow["app_id"].ToString().Equals("0"))
DRow["AppName_ID"] = "Select";
}

Get filtered data from dataset to datatable

How can I filter data from dataset to datatable?
like the code->
DataRow[] dr = DS.Tables[0]
.Select("STAGENAME='Develop' AND DEVLAPSEDAYS IS NOT NULL");
How can I use datatable here?
following code doesn`t reflect changes->
DataTable FilteredDataD = DS.Tables[0];
if (FilteredDataD.Rows.Count > 0) {
FilteredDataD.DefaultView.RowFilter = "STAGENAME='Develop' AND DEVLAPSEDAYS IS NOT NULL";
FilteredDataD.DefaultView.ToTable();
}
Is is possible to remove a column using above filter,like "STAGENAME='Develop' AND DEVLAPSEDAYS IS NOT NULL" + FilteredDataD.column("col_name")...
Suppose I have 5 columns display only 4,I can`t remove col_name from my query.Is there a way?
Reply
Try using LINQ instead:
var table = DS.Tables[0].AsEnumerable().Where(
r => r.Field<string>("STAGENAME") == "Develop" && r.Field<int?>("DEVLAPSEDAYS").HasValue).AsDataView().ToTable();
EDIT Changed AsDataView to AsDataView() for syntactical accuracy.
EDIT Provided .NET 2.0 compatible solution
DataTable table = DS.Tables[0];
if (table.Rows.Count > 0)
{
table.DefaultView.RowFilter = "STAGENAME = 'DEVELOP' AND DEVLAPSEDAYS IS NOT NULL";
table = table.DefaultView.ToTable();
}
You could write an extension method (using C# 3) like follows:
public static DataTable Filter(this DataTable dataTable, string selectFilter)
{
var filteredTable = dataTable.Clone();
var rows = dataTable.Select(selectFilter).ToList();
rows.ForEach(filteredTable.ImportRow);
return filteredTable;
}
Then use it like follows:
DataTable dataTable = DS.Tables[0]
.Filter("STAGENAME='Develop' AND DEVLAPSEDAYS IS NOT NULL");
Update, since you said you are using C# 2.0 (and thus extension methods and LINQ aren't an option) you could use this instead:
public static DataTable GetFilteredTable(
DataTable sourceTable, string selectFilter)
{
var filteredTable = sourceTable.Clone();
var rows = sourceTable.Select(selectFilter);
foreach (DataRow row in rows)
{
filteredTable.ImportRow(row);
}
return filteredTable;
}
DataTable dataTable = GetFilteredTable(
DS.Tables[0], "STAGENAME='Develop' AND DEVLAPSEDAYS IS NOT NULL");

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