【问题标题】:Convert an int to a string saved in a SQL Server database将 int 转换为保存在 SQL Server 数据库中的字符串
【发布时间】:2026-01-24 18:05:01
【问题描述】:

我有一个 SQL Server 数据库,其中有一个表 Event_Tab 和一个 IntCode。我想将这个Code 与一个特定的string 关联起来,这样我就不会在我的表中保存字符串变量。

所以,我用 In16 输入参数编写了一个过程GetStringCode,它返回了我需要的字符串,然后我用保存在我的表中的另一个参数将它填充到一个列表视图中

这是我的代码:

using (SqlConnection connection = new SqlConnection(connectionstring))
using (SqlDataAdapter adapter = new SqlDataAdapter(query, connection))
{
    DataTable table = new DataTable();
    adapter.Fill(table);

    foreach(DataRow dr in table.Rows)
    {
        ListViewItem items = new ListViewItem(dr["Machine"].ToString());                    
        items.SubItems.Add(GetStringCode((short)dr["Code"]).ToString());
        items.SubItems.Add(dr["Date_time"].ToString());
        listview.Items.Add(items);
    }
}  

如果你注意到,我做了一个演员来消除错误

无法从 object 转换为 short

到目前为止,一切似乎都还好。但是当尝试运行这段代码时,我得到一个错误

具体演员表无效

什么问题,因为我似乎找不到它......

【问题讨论】:

  • 发生错误时“DataRow dr”的内容是什么?可能 "Code" 为空或 null。
  • @Stringfellow,它不是空的,我检查了我的表格数据,它有数字
  • 首先在调试器中检查dr["Code"] 的值和实际类型。

标签: c# string listview int dataadapter


【解决方案1】:

如果 SQL 表正在为 Code 定义列,如下所示:

CREATE TABLE Event_Tab (
    Machine varchar(255),
    Code int,
    Date_time datetime
);

那么来自 SQL 的数据类型将不会转换为 C# 的 shortInt16,因为 SQL int 等效于 C# Int32 (Data Type Mapping)

static void Main(string[] args)
{
    DataTable table = new DataTable();
    table.Columns.Add("Machine", typeof(string));
    table.Columns.Add("Code", typeof(SqlInt32));
    table.Columns.Add("Date_time", typeof(DateTime));

    DataRow dr = table.NewRow();
    dr.ItemArray = new object[] { "machineA", 1122, DateTime.Now };

    // Works
    Int32 i32 = ((SqlInt32)dr["Code"]).Value;

    // Throws 'Specified cast is not valid.'
    Int16 i16 = (short)dr["Code"];
}

【讨论】:

  • 您是否建议将我的代码列类型更改为 SqlInt32?因为我什至没有这种列类型作为选择,而且我无法在 c# 中使用 SqlInt32 进行强制转换,所以它无法识别它
  • 不,不建议使用SqlInt32。试图演示 SQL 中的类型可能与 C# 中的类型不匹配,从而导致无效强制转换异常。希望暗示使用调试器更深入地挖掘从 SQL 和 DataTable 返回的数据类型。顺便说一句,SqlInt32using System.Data.SqlTypes;
【解决方案2】:

您可能会遇到拆箱问题,而不是类型转换。 int 类型的变量将转换为 short。但是,装箱的 int 不会直接转换为 short。装箱值类型只能直接转换为确切的装箱类型。

int i = 100;
object o = i; // Boxed int.
short s1 = (short) i; // Works.
short s2 = (short) o; // Throws InvalidCastException.
short s3 = (short) (int) o; // Works.

DataRow 将字段值存储为object,因此值类型被装箱。这意味着尝试将一个装箱 int 的字段值直接转换为 short 会导致问题。两阶段演员表(如上面的 s3)可以解决问题。

What is the difference between boxing/unboxing and type casting?

【讨论】:

  • 它成功了,谢谢,我会去检查装箱/拆箱,因为这是我第一次遇到它