James Brandon
James Brandon

Reputation: 1400

Invalid cast from string to guid - how to fix this?

Does anyone know why i might be getting this? im not an asp.net guy so trying to fix something for someone.

Exception Details: System.InvalidCastException: Invalid cast from 'System.String' to 'System.Guid'.

Source Error:

Line 135:        {
Line 136:            dataSet = new DataSet();
Line 137:            adapter.Fill(dataSet);
Line 138:        }
Line 139:        finally

Full C#

public DataSet pendingCourses()
    {
        DataSet dataSet = new DataSet();
        User user = (User)Context.Items["CurrentUser"];

        SqlConnection selectConnection = new SqlConnection(ConfigurationSettings.AppSettings["DBConnectStr"]);
        SqlDataAdapter adapter = new SqlDataAdapter("dbo.procUsersGetInProgressCourses", selectConnection);
        adapter.SelectCommand.CommandType = CommandType.StoredProcedure;

        // get results
        adapter.SelectCommand.Parameters.Add("@Limit", SqlDbType.Int).Value = 5;
        adapter.SelectCommand.Parameters.Add("@Culture", SqlDbType.VarChar, 6).Value = "en-GB";
        adapter.SelectCommand.Parameters.Add("@UserID", SqlDbType.UniqueIdentifier).Value = "EC9D439A-A084-48A4-80DD-80F7BB00AEF2";

        try
        {
            dataSet = new DataSet();
            adapter.Fill(dataSet);
        }
        finally
        {
            if (selectConnection.State == ConnectionState.Open)
            {
                selectConnection.Close();
            }
        }
        return dataSet;
    }

Upvotes: 2

Views: 2817

Answers (2)

Selman Genç
Selman Genç

Reputation: 101681

You can try:

 .Value = new Guid("EC9D439A-A084-48A4-80DD-80F7BB00AEF2");

The corresponding .NET Type of SqlDbType.UniqueIdentifier is System.Guid so you need to give it a value of type Guid.

Upvotes: 3

Jonesopolis
Jonesopolis

Reputation: 25370

try

adapter.SelectCommand.Parameters.Add("@UserID", SqlDbType.UniqueIdentifier).Value = Guid.Parse("EC9D439A-A084-48A4-80DD-80F7BB00AEF2");

the main point being

Guid.Parse("EC9D439A-A084-48A4-80DD-80F7BB00AEF2")

sql is expecting a uniqueidentifier (guid) and you're sending a string along. This will send the correct type.

Upvotes: 2

Related Questions