繁体   English   中英

输入字符串格式不正确,将字符串转换为C#中的long?

[英]input string was not in correct format converting string to long in c#?

大家好,我正在mvc4上工作,这里有些问题,一旦我将值存储在像'String []'这样的数组中,就从表单集合中获取值,我将这些值移动到我的数据库表中,但是我总是只有一个问题“输入字符串的格式不正确”,任何机构都可以帮助我

这里我的代码如下:

string[] BundleItemID = form.GetValues("txtbundleid");

for (int i = 0; i < skuid.Length; i++)
{
    ProductBundleItem productbundleitem = new ProductBundleItem();
    if (!string.IsNullOrEmpty(BundleItemID[i]))
    {
        productbundleitem.BundleItemId = Convert.ToInt64(BundleItemID[i]);
    }
}

当我尝试将值从“ Convert.ToInt64(BundleItemID [i])”移动到“ BundleItemId”时,我得到一个错误提示“输入字符串格式不正确”

您应该使用long.TryParse来检查是否可以进行转换,如下所示:

long val;
if (long.TryParse(BundleItemID[i], out val)
    productbundleitem.BundleItemId = val;
else
    // handle situation when BundleItemID[i] is not a number somehow

添加了调试MessageBox,以便您可以找到错误。

   string[] BundleItemID = form.GetValues("txtbundleid");

    for (int i = 0; i < skuid.Length; i++)
    {
        ProductBundleItem productbundleitem = new ProductBundleItem();
        if (!string.IsNullOrEmpty(BundleItemID[i]))
        {
            long val = 0;
            if (!long.TryParse(BundleItemID[i], out val))
            {
                MessageBox.Show(string.Format("{0} is not a valid Int64 value", BundleItemID[i]));
                break;
            }
            productbundleitem.BundleItemId = val;
        }
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM