0

Is it possible to use convert a string to a GUID via inline C# within ASP.NET? In this example I would like to pass in a string for CustomerId and have it formatted as a GUID as the stored procedure expects a Unique Identifier.

<asp:SqlDataSource ID="myDataSOurce" runat="server" ConnectionString="<%$ ConnectionStrings:myConnectionString %>" SelectCommand="GetUserData" SelectCommandType="StoredProcedure">
        <SelectParameters>
                <asp:Parameter DefaultValue="<% new Guid(customerId).ToString() %>" Name="CustomerId" Type="String" />
        </SelectParameters>
</asp:SqlDataSource>

When I try this I get an error from SQL Server:

Error converting data type nvarchar to uniqueidentifier.

DerStarkeBaer
  • 669
  • 8
  • 28
webworm
  • 10,587
  • 33
  • 120
  • 217
  • 1
    Sure, you can convert a string to a Guid in C#. Your error seems to be a type problem. I suspect declaring your parameter type as a string here is confusing it. – mason Aug 15 '19 at 18:56
  • Tried just using `new Guid(customerId)` initially but received the same error. Could the `new` keyword be the issue? – webworm Aug 15 '19 at 18:58
  • Maybe use a Binding Expression `DefaultValue='<%# new Guid(customerId).ToString() %>'` But why convert to a Guid and then call ToString on it, then it becomes `customerId` again basically. – VDWWD Aug 15 '19 at 19:03
  • I figured `.ToString()` would give me a string with the formatting present in a GUID (i.e. dashes). I also tried the binding syntax and it is rejected because the control doesn't implement `DataBind` – webworm Aug 15 '19 at 19:11
  • I think you want to use `Type="Object"` for a guid. (not confirmed) – mxmissile Aug 15 '19 at 20:13
  • If I hard code the GUID (i.e. 'XXXXX-YYYYYY-ZZZZZZZ-AAAAAAA') it works without issues – webworm Aug 15 '19 at 20:33

2 Answers2

1

Is it possible to modify your stored procedure to accept string and then cast the string to uniqueidentifier in your SQL code. If yes, check this answer

There are a couple of comments on that answer that achieve the same thing with less code. However, if that is not possible, see if this works.

<asp:SqlDataSource ID="myDataSOurce" runat="server" ConnectionString="<%$ ConnectionStrings:myConnectionString %>" SelectCommand="GetUserData" SelectCommandType="StoredProcedure">
    <SelectParameters>
            <asp:Parameter DefaultValue="<% System.Guid.Parse(customerId) %>" Name="CustomerId" DbType="Guid" />
    </SelectParameters>

GidiBloke
  • 478
  • 4
  • 16
0

Try this:

<asp:Parameter DefaultValue="<% Guid.NewGuid() %>" Name="CustomerId" Type="String" />
    </SelectParameters>
Tom
  • 163
  • 1
  • 11