0

I have a dropdownlist that gets populated with a varbinary(256) column from SQL Server. I send the selected value in this dropdownlist to a stored procedure, but I get the error

Invalid cast from 'System.String' to 'System.Byte[]'.

The C# code is calling a SP that runs this query to return the name and id to the dropdown list.

SELECT staffID, sAMAccountName,  (sn + ', ' + givenName) AS fullName
FROM staff
WHERE deleteEmployee = 'no' AND recordType = 'staff'
ORDER BY sn

I add the parameter as below.

objCmd.Parameters.Add("@staffID", SqlDbType.Binary).Value = ddl_staff.SelectedItem.Value;

If I go into SQL and execute the SP like below, I get the expected results.

DECLARE @staffID varbinary(256)
SELECT @staffID = staffID from staff where samaccountname = 'johndoe'
EXECUTE stp_nho_status @staffID

What is happening to the data when it is run by the asp.net page; is it converted to a string in the dropdownlist value? Do I have to convert it somehow?

3
  • If you set a breakpoint and inspect the value of ddl_staff.SelectedItem.Value, what do you get? Commented Jan 6, 2015 at 20:11
  • have you checked the value of SelectedItem.Value of the dropdowmlist, the value use to be a string in the parameters you need a Binary and youre adding string value,in your query you should convert the SelectedItem.Value to binary, can you checked Commented Jan 6, 2015 at 20:12
  • Also, wonder if the parameter should be SqlDbType.VarBinary since it's declared as a varbinary in your SQL? Commented Jan 6, 2015 at 20:57

1 Answer 1

1

You might consider writing a method that converts a string to a byte[] (which can be converted to a SqlDbType.VarBinary):

public static byte[] StrToByteArray(string value)
{
    System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
    return encoding.GetBytes(value);
}

Then you could use it like:

objCmd.Parameters.Add("@staffID", SqlDbType.VarBinary).Value = 
    StrToByteArray(ddl_staff.SelectedItem.Value);
Sign up to request clarification or add additional context in comments.

3 Comments

Does ASP.NET convert the varbinary to a string when it is populated in the dropdownlist? I tried as you suggested, I returned no results where I expected them. I inserted the staffID being passed to the SP in a temp table, and it looks different than what would have been coming out of the staff table, some conversion issue?
Sounds like a conversion problem. What does the inserted value look like compared to the pre-conversion string value?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.