Good day,
IDE Visual Studio 2010
.NET 3.5
Platform WinForms
The SO question ” difference between getting value from DataRow ” refers.
I have a database table with a column [ID] INT IDENTITY(1, 1) NOT NULL PRIMARY KEY. When querying this table and storing the values in local variables I get an invalid cast exception; sample code:
string sQuery = @"
SELECT [ID], [Description]
FROM [Sources]
ORDER BY [Description] ";
using (DataTable dtSources = SQLHelper.Fetch(sQuery))
{
foreach (DataRow drSource in dtSources.Rows)
{
int iID = drSource.Field<int>("ID"); // InvalidCastException
string sDescrption = drSource.Field<string>("Description");
}
}
When stepping the execution and performing a “Quick Watch” on the faulty line I discovered that, by changing the line to drSource.Field<object>("ID"), the cell value type is that of short and not of int. Why would this happen when, in the table definition, this is clearly and int? Furthermore, short should be implicitly converted to int since short is smaller and should “fit” right?
Out of curiosity, what happens if you explicitly cast it yourself from the key/value collection?