0

I have the following piece of code:

string ConnString = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
string SqlString = "Select * From Memberships WHERE ApplicationId =  @username";
using(SqlConnection conn = new SqlConnection(ConnString)) {
  using(SqlCommand cmd = new SqlCommand(SqlString, conn)) {
    cmd.CommandType = CommandType.Text;
    SqlParameter param = new SqlParameter();
    param.ParameterName = "@username";
    param.Value = UserName2.Text;
    cmd.Parameters.Add(param);
    conn.Open();
    using(SqlDataReader reader = cmd.ExecuteReader()) {
      test.DataSource = reader;
      test.DataBind();
    }
  }
}

In this case the codes breaks on DataBind() with the following error: Conversion failed when converting from a character string to uniqueidentifier. This is caused because I'm using the ApplicationId in my query instead of the UserName. With the UserName all works fine.

I know that the GUID is causing the error, but I don't know why and how to fix it.

MikO
  • 18,243
  • 12
  • 77
  • 109
MartinH
  • 1,440
  • 13
  • 24

1 Answers1

0

What is type of AplicationId in your db? If guid - your problem is comparing string parameter to guid. Cast one of them.

Something like convert(nvarchar(50), ApplicstionID)

See also SQL Server: converting UniqueIdentifier to string in a case statement

Community
  • 1
  • 1
evgenyl
  • 7,837
  • 2
  • 27
  • 32