来自 TextBox 的 ADO.NET 参数
我试图在我的 C# Winforms 应用程序中从 SQL Server 2005 调用参数化存储过程。我从 TextBoxes 添加参数,如下所示(有 88 个):
cmd.Parameters.Add("@CustomerName", SqlDbType.VarChar, 100).Value = CustomerName.Text;
我得到以下异常:
"System.InvalidCastException: Failed to convert parameter value
from a TextBox to a String. ---> System.InvalidCastException:
Object must implement IConvertible."
抛出错误的行是当我调用查询时:
cmd.ExecuteNonQuery();
我还尝试在 TextBoxes 上使用 .ToString() 方法,这似乎毫无意义无论如何,并抛出同样的错误。我传递的参数不正确吗?
I'm trying to call a parameterized stored procedure from SQL Server 2005 in my C# Winforms app. I add the parameters from TextBoxeslike so (there are 88 of them):
cmd.Parameters.Add("@CustomerName", SqlDbType.VarChar, 100).Value = CustomerName.Text;
I get the following exception:
"System.InvalidCastException: Failed to convert parameter value
from a TextBox to a String. ---> System.InvalidCastException:
Object must implement IConvertible."
The line throwing the error is when I call the query:
cmd.ExecuteNonQuery();
I also tried using the .ToString() method on the TextBoxes, which seemed pointless anyway, and threw the same error. Am I passing the parameters incorrectly?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可能在分配参数值之一时忘记指定
Text
属性。例如,而不是:
您可能只做了:
如果有 88 个,这将很容易错过。
It's probable that you forgot to specify the
Text
property when assigning one of your parameter values.For example, instead of:
You may have done just:
This would be an easy thing to miss if there are 88 of them.
我怀疑你在某个地方错过了 .Text,但你说你对所有参数值都做了 ToString,所以这看起来很奇怪。无论如何,您可以使用以下代码来转储参数名称和值的类型名称,这可能有助于发现有问题的参数。
您应该在调试窗口中看到类似以下内容的内容,在本例中,CustomerSurname 是具有文本框而不是字符串的参数作为示例。
I suspect you have missed a .Text somewhere, but you say you did a ToString on all the parameter values so that seems strange. Anyway, you can use the following piece of code to dump the parameter names and the type name of the value, this might help spot the problematic parameter.
You should get something like the following in the debug window, in this case CustomerSurname is the parameter that has a Textbox and not a string as an example.
尝试这样的事情:
try something like this: