【问题标题】:converting datatable object to int将数据表对象转换为 int
【发布时间】:2019-03-16 03:56:09
【问题描述】:

我有 foreach 循环,我试图将从包含 id 的 sql 中获取的对象分配给我的列表模型,其中该项目必须是 int。

 foreach (DataRow item in dtbProduct.Rows)
            {
                PaymentsList.Add(new Payments()
                {
                    PaymentID = item["p_ID"],

在这种情况下我得到语法错误

不能简单地将 objecto 转换为 int

但如果我写

PaymentID = int.Parse(item["p_ID"].ToString()),

项目运行但我收到运行时错误

System.FormatException: '输入字符串的格式不正确。'

【问题讨论】:

  • item["p_ID"].ToString() 的值是多少?
  • 向我们展示 item["p_ID"].ToString() 的值
  • p_ID 是什么数据类型?由于它可能用作数据库中的主键,我假设这是一个 int64?在这种情况下使用 int64.Parse()
  • 你试过 Convert.ToInt64(item["p_Id"]) 吗??
  • 做到了,但语法说不能将 long 隐式转换为 int

标签: c# sql type-conversion int


【解决方案1】:

您可以使用 int.TryParse 代替 int.Parse - 阅读 https://www.dotnetperls.com/parse

或者如果它是一个很长的尝试 long.TryParse

研究 .net 中的数据类型到 sql server 的映射以确定您需要什么

【讨论】:

    【解决方案2】:

    如果它是 sql 中的 Int,那么可能存在一些 null 值,这在转换时会出错。在转换为 int 之前尝试检查 null

    前-

    PaymentID = Convert.ToInt32( string.IsNullOrEmpty(item["p_ID"].ToString()) ? "0" : item["p_ID"].ToString()); // provided 0 if null
    

    试试这个

    【讨论】:

    • 这对我有用,可能我的选择给了我空值,这会导致问题。
    猜你喜欢
    • 2020-06-12
    • 1970-01-01
    • 2014-12-02
    • 2017-09-26
    • 1970-01-01
    • 1970-01-01
    • 2011-04-09
    • 1970-01-01
    • 2021-08-01
    相关资源
    最近更新 更多