4
DataTable dtt = (DataTable)Session["ByBrand"];
var filldt = (dtt.Select("Price >= " + HiddenField1.Value + " and Price <= " + HiddenField2.Value + "")).CopyToDataTable();

this code is working fine when it found values in selected DataTable but it showing error when Values are not found in DataTable. So please tell me how to check if no record found.

1
  • What error are you getting? Seems like the CopyToDataTable() extension method should return an empty DataTable even if the result was empty instead of erroring out. Commented Jun 3, 2013 at 10:22

2 Answers 2

6

Simply check if your Select returns anything?

 DataTable dtt = (DataTable)Session["ByBrand"];
 DataRow[] rows = dtt.Select("Price >= " + HiddenField1.Value + " and Price <= " + HiddenField2.Value + "");
if(rows.Length > 0)
{
    var filldt = rows.CopyToDataTable();
}

Well, the Linq example from Tim is really nice, but to complete my answer. The Select method returns Always a DataRow array also if there is no row selected, but then you cannot ask to build a datatable from this empty array. Think about it. What schema the CopyToDataTable should build for the resulting table if no rows are present in the array?

Sign up to request clarification or add additional context in comments.

Comments

6

You have tagged Linq but you are using DataTable.Select which is an old method to filter a DataTable. Use Enumerable.Where and the strongyl typed Field extension method.

decimal priceFrom = decimal.Parse(HiddenField1.Value);
decimal priceTo = decimal.Parse(HiddenField2.Value);

var dtFiltered = dtt.AsEnumerable()
    .Where(row => row.Field<decimal>("Price") >= priceFrom 
               && row.Field<decimal>("Price") <= priceTo))
    .CopyToDataTable();

Presuming that the type of the column is decimal, if it's a different type you need to use that in Field or convert it first.

Note that you need to add System.Linq(file) and a reference to System.Data.DataSetExtensions(project).

Update

but it showing error when Values are not found in DataTable

CopyToDataTable throws an exception if the input sequence is empty. In my opinion the best approach is to handle that case separately:

DataTable tblFiltered = dtt.Clone(); // clones only structure not data
var filteredRows = dtt.AsEnumerable()
    .Where(row => row.Field<decimal>("Price") >= priceFrom 
               && row.Field<decimal>("Price") <= priceTo));
if(filteredRows.Any())
{
    tblFiltered = filteredRows.CopyToDataTable();
}

or this approach that might be more efficient since it doesn't need to use Any which can cause an additional full enumeration in worst case:

foreach(DataRow row in filteredRows)
{
    tblFiltered.ImportRow(row);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.