Index Out of Bound Exception could occur when you are using DataTable select() method for DataTable filtering purposes. Issue occurs when there are no matching data rows satisfying the condition.
Imagine we have data in our DataTable in below tabular format
Name
|
Address
|
Age
|
Chmara
|
Kandy
|
27
|
Janaka
|
Colombo
|
25
|
Gihan
|
Kadawath
|
26
|
Now we try to filter the DataTable
DataTable DT=new DataTable();
DT=getdata();//Method for retrieving data from database
DataRow[] DR=DT.select("Name=Asanka");
In this case DataTable returns no rows so the exception occurs. To avoid this we can use LINQ for DataTable filtering purpose. Then it returns an empty DataTable so that the exception does not occur.
DT= DT.AsEnumerable().Where(r => r.Field<string>("Name") == "Asanka").AsDataView().ToTable();
Above solution supports only in below versions of .NET framework
.NET Framework
Supported in: 4.5, 4, 3.5
.NET Framework Client Profile
Supported in: 4, 3.5 SP1
No comments:
Write comments