-1

I am getting a error "Conversion failed when converting the nvarchar value 'UDAYA' to data type int." I tried to sort it out by adding Convert.ToInt32(); but it didn't worked out. My Code looks like

SqlConnection connection = new SqlConnection(connectionstring);
        connection.Open();
        SqlCommand cmd = new SqlCommand(("select MenuId from MenuPermissionTable where UserId=@UserId"), connection);
        cmd.Parameters.AddWithValue("@UserId",Login.userid_string);
        Convert.ToString("@UserId");
        SqlDataAdapter adp = new SqlDataAdapter(cmd);
        adp.SelectCommand = cmd;
        DataSet ds = new DataSet();
        adp.Fill(ds);
  • 2
    It is an sql error. – SᴇM Nov 14 '18 at 08:54
  • 4
    Possible duplicate of [Conversion failed when converting the nvarchar value ... to data type int](https://stackoverflow.com/questions/21655110/conversion-failed-when-converting-the-nvarchar-value-to-data-type-int) – SᴇM Nov 14 '18 at 08:55
  • may be your `UserId` in table is of `int` type, and the value you are passing in `@UserId` parameter is not `int` type. Looks like `Login.userid_string` has value `UDAYA` which can't be converted to `int` – Deepak Sharma Nov 14 '18 at 08:58
  • What is the purpose of this line `Convert.ToString("@UserId");`? You're not assigning it to a variable and even if you did you're trying to [convert a string to another string](https://learn.microsoft.com/en-us/dotnet/api/system.convert.tostring?view=netframework-4.7.2#System_Convert_ToString_System_String_). – ikerbera Nov 14 '18 at 09:00
  • What is the value of `Login.userid_string`? – mjwills Nov 14 '18 at 09:15
  • use exec sp_help 'MenuPermissionTable' in your database. Check what is the type of the column UserId. If that is int, then you cant pass a string to it. I would suggest you should get the userId from Udaya and pass to this query – Praneet Nadkar Nov 14 '18 at 09:57

1 Answers1

0

The error caused by "@UserId" parameter failed in Database transformation.

I would use the Add method instead of AddWithValue method

because Add method can set your parameter Type and size in Database

cmd.Parameters.Add("@UserId", SqlDbType.Int,0).Value = Login.userid_string;

NOTE

Try to set a correctly enum SqlDbType value be the parameter, which as same as your this parameter type.

D-Shih
  • 44,943
  • 6
  • 31
  • 51