Unrecognized Guid Format Error in Asp. Net?

Hello all I am facing this problem in asp.net project . "System.FormatException: Unrecognized Guid format. at System.Guid.GuidResult.SetFailure(ParseFailureKind failure, String failureMessageID, Object failureMessageFormatArgument, String failureArgumentName, Exception innerException) at System.Guid.TryParseGuid(String g, GuidStyles flags, GuidResult& result) at System.Guid..ctor(String g) at UserAuthentication.HumanResources.ViewAllJobs() in HumanResources.cs:line 105"

my code and store procedure for HumanResource.cs is as follows First one is HumanResource code second is store procedure

       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

8

1 Answer

The error is on this line:

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

You could put a guard clause in your code to not add hr objects if they do not have a valid guid:

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Chloe Bennett

Chloe Bennett

Culture, Media & Entertainment Columnist

Chloe Bennett explores the intersection of pop culture, streaming entertainment, digital trends, and contemporary lifestyle. Her weekly commentary reaches thousands of culture enthusiasts.

Share this article
Twitter Facebook Pinterest