将数据表对象转换为 int



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

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

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

不能简单地将对象转换为 int

但是如果我写

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

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

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

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

前任-

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

试试这个

而不是int。解析你可以使用 int。TryParse - 读取 https://www.dotnetperls.com/parse

或者如果这是一个漫长的尝试。TryParse

研究 .NET 中数据类型到 SQL Server 的映射,以确定您需要的内容

最新更新