Anup
Anup

Reputation: 9738

MVC C# - DataTable in DataRows with Condition

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?

enter image description here

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);
                    }

Upvotes: 1

Views: 1742

Answers (3)

LPs
LPs

Reputation: 16223

Try with Linq:

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

Upvotes: 0

Alex Walker
Alex Walker

Reputation: 2356

The != operator is not supported by the RowFilter syntax.

Try:

DataRow[] HeadingFields = datatable.Select("NOT (HeaderPrintOrder = 0)");

Upvotes: 0

Tim Schmelter
Tim Schmelter

Reputation: 460208

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

Upvotes: 3

Related Questions