C# combobox value to pass to SQL parameter

僤鯓⒐⒋嵵緔 提交于 2020-01-06 19:55:30

问题


This question is related to my previous one here:

Populating C# combobox from SQL and restrict results based on choice

hoping to get more attention. Given a combobox from which I'd like to pass the value. On the SelectedIndexChange property I put a method, which calls a Stored Procedure from SQL.

SqlCommand command;

command.Parameters.Add("@someparameter", combobox1.GetItemText(combobox1.SelectedItem));

command.CommandText = "StoredProcedure1";

command.ExecuteNonQuery();

Well, it takes no effect. Anyone to point out what I'm doing wrong/missing? Thank you


回答1:


You have an SQL command and a parameter. You execute the command, but into what connection?

It's like me starting my engine, but I haven't actually got the rest of the car to drive. I can turn it on, but without a car I can't drive.

You can fix this by doing something like this:

SqlCommand newCmd = new SqlCommand("SELECT @someParameter from DATABASE", conn);

Notice the , conn at the end of the above command. This allows you to use a method such as ExecuteNonQuery(), and the command knows which connection to use for its query.



来源:https://stackoverflow.com/questions/40769430/c-sharp-combobox-value-to-pass-to-sql-parameter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!