[英]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. 我有一个下拉列表,其中装有SQL Server的varbinary(256)列。 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[]'.
从“ System.String”到“ System.Byte []”的无效转换。
The C# code is calling a SP that runs this query to return the name and id to the dropdown list. C#代码正在调用运行此查询的SP,以将名称和ID返回到下拉列表。
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. 如果我进入SQL并执行如下所示的SP,我将获得预期的结果。
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; 当数据由asp.net页运行时,该怎么办? is it converted to a string in the dropdownlist value?
是否将其转换为dropdownlist值中的字符串? 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
): 您可能考虑编写一种将
string
转换为byte[]
(可以将其转换为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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.