输入字符串格式不正确在c#中将字符串转换为long?

时间:2012-12-28 07:49:03

标签: c#

大家好我正在研究mvc4我在这里有一些问题我从表单集合中获取值 一旦我得到了这些值,我将存储在数组中,如'String []',从那些iam movint那些 值到我的数据库表,但我总是只有一个问题'输入字符串格式不正确' 任何身体可以帮助我PLZ

这里我的代码遵循:'

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'时,我收到错误   '输入字符串格式不正确' 提前谢谢

2 个答案:

答案 0 :(得分:1)

您应该使用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

答案 1 :(得分:1)

添加了一个调试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;
        }
    }