Datatable Select returning Array Index out of bounds

This line:

searchParamsTable.Select(string.Format("TABLE = {0} AND FIELD = '{1}'", tableNumbers[i], fieldName[i]))[0]["VALUE"] = wildcardedSearchString;

returns an Array Index out of bounds exception in C#. How can I write this to not throw the error? Or is there an alternate way I can write this if no records are returned to continue execution of the code? I search through three different tables for result using line with 'i' as the increment of the table and field names.

Answers


This is incomplete, how should we know what tableNumbers,fieldName and wildcardedSearchString are? The exception is probably thrown at tableNumbers[i], fieldName[i] or the [0] indexer of the select.

I assume that the select doesn't return rows, so [0] will throw an IndexOutOfBounds exception.

You could use Steves approach or use Linq-To-Dataset which is more readable and powerful:

IEnumerable<DataRow> rows = searchParamsTable.AsEnumerable()
                         .Where(r => r.Field<String>("TABLE") == tableNumbers[i] 
                                 &&  r.Field<String>("FIELD ") == fieldName[i]);
if(rows.Any())
{
    // do something with the rows, for example create a new DataTable from the result:
    DataTable tblSearch = rows.CopyToDataTable();
}

Supposing your i index var is right then you should check if any row is returned from the Select statement

DataRow[] rows = searchParamsTable.Select(string.Format("TABLE = {0} AND FIELD = '{1}'", 
                 tableNumbers[i], fieldName[i]));

if(rows.Length > 0)
   rows[0]["VALUE"] = wildcardedSearchString;

You are doing quite a lot of array indexing in that statement, so exactly which one that is out of bounds is hard to tell. Are you sure i is a valid index into both tableNumbers and fieldName ?

Try breaking the statement up into separate lines, then use the debugger to find out.


Need Your Help

Dot separated clientside date validation in asp MVC 4

asp.net-mvc validation datetime localization client-side

So I've been banging my head to wall with this problem for hours. I'm creating localized validation for my date input fields. I've overwritten the default jquery date validator and the method seems...

Storing a timestamp as a default value in hstore

postgresql hstore

I am trying to store the current timestamp as a default value in an hstore. I tried using now() but all that is stored is "last_collected"=&gt;"now()". Here is what I have: