Field<int>指定转换无效问题求助:C# DataTable中NUMERIC字段转int失败
Hey there, let's break down why you're hitting this casting error and how to fix it!
The Root Cause
Your CUDOC_NUMBER column is defined as NUMERIC in the database, and ADO.NET maps NUMERIC types to decimal by default—not int. The Field<int>() method does a strict type check: it expects the underlying value to be exactly an int, so trying to cast a decimal directly to int here throws the "specified cast is not valid" exception.
Possible Solutions
1. Convert from decimal to int (safe if values fit in int range)
If you're sure the CUDOC_NUMBER values never exceed the int limit (-2,147,483,648 to 2,147,483,647), you can first fetch the decimal value then convert it to int:
if (table != null && table.Rows.Count > 0) { string origin = table.Rows[0].Field<string>("CUDOC_ORIGIN"); decimal numberDecimal = table.Rows[0].Field<decimal>("CUDOC_NUMBER"); int numberInt = Convert.ToInt32(numberDecimal); lblCudoc.Text = $"{origin}-{numberInt}"; }
2. Use decimal directly (no conversion needed)
If you don't strictly need an int, you can just use the decimal type directly when building your string—this avoids any conversion issues entirely:
if (table != null && table.Rows.Count > 0) { lblCudoc.Text = $"{table.Rows[0].Field<string>("CUDOC_ORIGIN")}-{table.Rows[0].Field<decimal>("CUDOC_NUMBER")}"; }
3. Handle possible DBNull values
If there's a chance CUDOC_NUMBER could be null in the database, add a check to avoid null reference or casting errors:
if (table != null && table.Rows.Count > 0) { string origin = table.Rows[0].Field<string>("CUDOC_ORIGIN"); object numberValue = table.Rows[0]["CUDOC_NUMBER"]; string numberText = numberValue != DBNull.Value ? numberValue.ToString() : "0"; // Replace with your preferred default lblCudoc.Text = $"{origin}-{numberText}"; }
4. Check for out-of-range values
If your NUMERIC column stores values larger than int's max, use long instead of int to prevent overflow:
long numberLong = table.Rows[0].Field<long>("CUDOC_NUMBER");
Quick Tip
Always double-check the database column's data type and its corresponding .NET type mapping—ADO.NET has strict rules for these, and mismatches are a common source of casting errors!
内容的提问来源于stack exchange,提问作者Pablo Bongiolatti

