1

I am having trouble SELECTing a column of type uniqueidentifier and putting it in a variable of type Guid in ASP.net.

The database is generating the uniqueidentifier, and all I want to do is pull them out and store the values in case I need to populate a foreign key table.

I am using a private member to store the value:

Private _uniqueID as guid 

I SELECT from the table and use a SqlDataReader called vRdr. All the other values are coming out just fine, but when I add this I get an error:

if not isDBNull( vRdr("uniqueID")) then _uniqueID = vRdr.GetGuid("uniqueID") end if 

The error I get is

Input string was not in a correct format.

I am not sure why I am having so much trouble trying to select these values. I have also tried Guid.Parse() and Guid.TryParse() on the data reader value with no luck.

Thanks for reading.

4 Answers 4

3

According to the MSDN docs, GetGuid() takes a column ordinal, not a string key. Change your code to this:

_uniqueID = vRdr.GetGuid(vRdr.GetOrdinal("uniqueID")) 
Sign up to request clarification or add additional context in comments.

2 Comments

Awe, that's the sort of learning that doesn't scale well beyond RTFM. Thank you, this works.
Post your code and any errors as a new question, and we can take a look at resolving the issue.
1

Have you tried creating a new Guid from your database value?

Example:

_uniqueID = New Guid(vRdr("uniqueID").ToString()) 

2 Comments

I had tried new Guid( "" & vRdr("uniqueID")) but not .ToString( ). Your code works, but another correct answer was first. I don't think I can check both.
I agree mgnoonan's answer is a better solution. Glad to help :)
0

If you're calling GetOrdinal() in a loop (for X records in a result set), this can be very costly. You'd want to save off the value of GetOrdinal() once and reuse.

Or, you can use the [] operator on IDataReader and index in given the string identifier for your column. This return an object, but simply cast it to a Guid. Note that indexing by string also calls GetOrdinal, at least in SqlDataReader.

Guid myGuid = (Guid)vRdr["uniqueID"]; 

Comments

0

often times many procedures works out for many versions of .net framework. Below is the two solutions that actually worked for me visual studio 2012.

  1. ViewState("Guid variable") = ("Guid value")
  2. Dim myGuid As Guid myGuid = ("Guid value")

The first solution retains the variable data after page postback while the second does not. Enjoy!

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.