将datatable对象转换为int

时间:2018-10-11 06:38:05

标签: c# sql type-conversion int

我有一个foreach循环,试图将包含id的sql对象分配给该项目必须为int的列表模型。

def addtoarray_bincount_zerosinit(shp, vol_coords, z_index=0):
    # shp is shape of voxel_space, desired output
    idx = vol_coords[:,0]*shp[2] + vol_coords[:,1] + z_index*shp[2]*shp[1]
    voxel_space = np.bincount(idx, minlength=np.prod(shp)).reshape(shp)
    return voxel_space

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

  

不能简单地将objecto转换为int

但是如果我写

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

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

  

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

2 个答案:

答案 0 :(得分:0)

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

或者如果尝试很长时间,请尝试。

.net中的数据类型到SQL Server的研究映射,以建立所需的内容

答案 1 :(得分:0)

如果在SQL中是Int,则可能存在一些null值,在转换时会出错。尝试先检查null的值,然后再转换为int

ex-

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

尝试一下

相关问题