Can someone assist me with the logic to validate the rowindex is in range and also valid the columnName? How would I do that with the logic below.
The task is to create my own custom exception derived from ApplicationException. However for this thread I am looking for the robust logic to valid index and column name.
public static int GetIntValue(this DataTable datatable, int rowindex, string columnName)
{try
{
//if index is out bounds throw out of bounds;
// return what is asking for
if (datatable != null)
{
if (rowindex > -1 && rowindex < datatable.Rows.Count - 1)
{
return Convert.ToInt32(datatable.Rows[rowindex][columnName]);
}
else
{
//return custom exception
}
}
else
{
//return custom exception
}
}
catch (Exception ex)
{
throw new Exception("GetIntValue: \n" + ex.Message);
}
}
VulpesPosted Dec 16, 2014, 5:31 AM
throw new ArgumentNullException("datatable", "Datatable is null.");
The point here is that there is a difference between a datatable being empty (i.e. it exists but has no rows) and being null i.e. there is no datatable at all.
An attempt to get a value from an empty datatable will be picked up as an 'out of range' error which would be the usual situation in the .NET Framework classes.
David SmithPosted Dec 15, 2014, 11:33 PM
public static int GetValueInt(this DataTable datatable, int rowindex, string columnName)
{
try
{
//Standard null exception
if (datatable == null)
throw new ArgumentNullException("datatable", "Datatable is empty.");
//Standard out of range exception for rows
if (rowindex < 0 || rowindex >= datatable.Rows.Count)
throw new ArgumentOutOfRangeException("rowindex", "Row index is out of range.");
//Standard out of range exception for column
if (!datatable.Columns.Contains(columnName))
throw new ArgumentOutOfRangeException("columnName", "Column does not exist.");
return Convert.ToInt32(datatable.Rows[rowindex][columnName]);
}
catch (Exception ex)
{
throw new Exception("GetValueInt: \n" + ex.Message);
}
}
VulpesPosted Dec 15, 2014, 6:36 PM