简体   繁体   中英

Error Invalid cast from 'System.String' to 'System.Byte[]' in C# calling stored procedure

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?

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM