asp.net中无法识别的Guid格式错误?

时间:2015-01-05 17:51:09

标签: c# asp.net

大家好,我在asp.net项目中遇到了这个问题。 “System.FormatException:无法识别的Guid格式。   在System.Guid.GuidResult.SetFailure(ParseFailureKind失败,String failureMessageID,Object failureMessageFormatArgument,String failureArgumentName,Exception innerException)   在System.Guid.TryParseGuid(String g,GuidStyles标志,GuidResult&结果)   在System.Guid..ctor(String g)   at HumanResources.cs中的UserAuthentication.HumanResources.ViewAllJobs():第105行“

HumanResource.cs的代码和存储过程如下  第一个是HumanResource代码,第二个是存储过程

       public static List<HumanResources> ViewAllJobs()
    {
        SqlConnection conn = new       SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString);
        SqlCommand cmd = new SqlCommand("spHumanResourcesViewAllJobs", conn);
        cmd.CommandType = CommandType.StoredProcedure;
        List<HumanResources> jobs = new List<HumanResources>();
        try
        {
            conn.Open();
            SqlDataReader rdr = cmd.ExecuteReader();
            while (rdr.Read())
            {
                HumanResources hr = new HumanResources();
                hr.jobTitle = rdr["JobTitle"].ToString();

               Guid guid = new Guid(rdr["Guid"].ToString());
                hr.guid = guid;
                jobs.Add(hr);
            }
        }
        catch (Exception ex)
        {
            throw new Exception(ex.ToString());
        }
        finally
        {
            cmd.Dispose();
            conn.Close();
        }
        return jobs;
    }


             Store Procedure:
                 CREATE PROCEDURE spHumanResourcesViewAllJobs 
         AS
           BEGIN

SET NOCOUNT ON;


SELECT Guid,JobTitle
FROM HR
WHERE Active=1

END GO

1 个答案:

答案 0 :(得分:2)

错误在这一行:

Guid guid = new Guid(rdr["Guid"].ToString());

您可以在代码中放置一个保护子句,以便在没有有效guid时添加hr个对象:

Guid guid;
if (Guid.TryParse(rdr["Guid"].ToString(), out guid))
{
    hr.guid = guid;
    jobs.Add(hr);
}