问题
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