Click here to Skip to main content
15,893,487 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi All,
I am using this linq to filter rows from data table.
C#
var result = from myRow in dtInventory.AsEnumerable()
 where myRow.Field<string>("Description").StartsWith(letters[0].ToString(), StringComparison.OrdinalIgnoreCase)
select myRow;



when the dtInventory is filled from a SQL table the Query works fine. but when I fill data table by SQL view the Query Throw exception like

"Object reference not set to an instance of an object"


How to resolve the issue??


Regards,
Palraj M.
Posted
Comments
Alexander Dymshyts 25-Jul-13 8:41am    
may be dtInventory is null? Check in debug where you get this error
palraj001 25-Jul-13 9:12am    
no dtinventory is not null. it has rows
Kuthuparakkal 25-Jul-13 9:32am    
What's this "letters[0].ToString()" ? Replace this with some letter may reveal the issue
palraj001 25-Jul-13 9:51am    
sorry.letters is an array . assume any letter for E.g letters[0] ="H"
Kuthuparakkal 25-Jul-13 10:50am    
Check the spelling for "Description" in your datatable against the Linq written

1 solution

We need to do some basic breaking down of the problem: Declare a temporary variable

C#
var foo = from myRow in dtInventory.AsEnumerable() select myRow;

Put on a breakpoint on the above and execute, if foo has rows then you've a different problem so move on. Relying on the table having data is no good. Though I doubt this is your problem, you just get a null or empty value in result
Step 2 is to replace letters[0].ToString() with *any* letter, e.g. "a" (as per Kuthuparakkal suggestion). If you don't get the exception, your array is null at the very least.

If you do get an exception then the problem is myRow.Field<string>("Description") is returning null. You've then got two immediate culprits to investigate: either your field name doesn't match (case sensitive?) or the field itself allows null (loop over the unfiltered results and get each value in turn to see).


If all this fails to diagnose your problem, the only other thing that leaps out is the dtInventory.AsEnumerable(), if this causes myRow to lose the it's column information/context, the .Field<t></t> won't work. This is very unlikely (I've not used this method) given that your code builds, but you could try re-removing the where clause and looping through the unfiltered results, inspecting each DataRow object in turn.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900