ASP.NET C#: SqlDataSource with Stored Procedure and Parameters

醉酒当歌 提交于 2019-12-14 04:08:34

问题


I am trying to have a SqlDataSource coded programmatically with stored procedure and with parameters. Later I want to assign this SqlDataSource to a listbox as a datasource.But I am getting an error that the stored procedure needs a parameter that wasn't supplied. I do not understand why its giving me the error despite supplying it.

The Code I am using is as below:

sqlDS = new SqlDataSource();
sqlDS.ConnectionString = DC.ConnectionString;
sqlDS.SelectCommandType = SqlDataSourceCommandType.StoredProcedure;
sqlDS.SelectParameters.Add("@aPara_Name", TypeCode.String, aPara_Value);
sqlDS.SelectParameters[0].Direction = ParameterDirection.Input;
sqlDS.SelectCommand = "usp_StoredProcedure_1";
sqlDS.DataBind();
this.Controls.Add(sqlDS);

Listbox1.DataSource = sqlDS;
Listbox1.DataTextField = "Title";
Listbox1.DataValueField = "Value";
Listbox1.DataBind();   //this is where I get the error saying that stored procedure requires a parameter that wasn't passed!

can someone guide me where I am going wrong?


回答1:


Could you try this approach instead?

                var com = new SqlConnection(DC.ConnectionString).CreateCommand();
                com.CommandType = CommandType.StoredProcedure;
                com.CommandText = @"usp_StoredProcedure_1";
                com.Parameters.Add("@aPara_Name", SqlDbType.VarChar, 20).Value = aPara_Value;

                var table = new DataTable();

                new SqlDataAdapter(com).Fill(table);

                Listbox1.DataSource = table;



回答2:


I was having the exact same problem and finally got the answer. It's simply a matter of not inserting the "@" sign when you declare the parameter in the "SelectParameters.Add()" method. So all you would have to do is to change the following line from:

sqlDS.SelectParameters.Add("@aPara_Name", TypeCode.String, aPara_Value);

to:

sqlDS.SelectParameters.Add("aPara_Name", TypeCode.String, aPara_Value);

Hope this helps.




回答3:


I agree with @kumbaya. Faced the same issue. Removed the @, and it worked fine.

Your code at line 4 should be edited as

sqlDS.SelectParameters.Add("aPara_Name", TypeCode.String, aPara_Value);


来源:https://stackoverflow.com/questions/17187581/asp-net-c-sqldatasource-with-stored-procedure-and-parameters

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