【问题标题】:ASP.NET C#: SqlDataSource with Stored Procedure and ParametersASP.NET C#:带有存储过程和参数的 SqlDataSource
【发布时间】:2013-06-19 09:24:07
【问题描述】:

我正在尝试使用存储过程和参数以编程方式对 SqlDataSource 进行编码。稍后我想将此 SqlDataSource 作为数据源分配给列表框。但我收到一个错误,即存储过程需要一个未提供的参数。我不明白为什么尽管提供了它却给了我错误。

我使用的代码如下:

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!

谁能指导我哪里出错了?

【问题讨论】:

  • 你能提供你的sp代码吗?
  • @Serge - 给你CREATE PROCEDURE usp_StoredProcedure_1 @aPara_Name varchar(20) AS SELECT * FROM aTable WHERE (SUBUNI = @aPara_Name) AND (SUBWON LIKE '____')
  • TypeCode.String... 出于好奇,您能否尝试使用 SqlDbType(即 SqlDbType.Varchar)?
  • @Serge,请问语法是什么?对于 .Add 方法?
  • 实际上我认为问题在于您必须将参数绑定到控件(或 coocki、查询字符串……),因为它会尝试检索该绑定元素的值。如果不存在这样的元素,则 SqlDataSource 可能不是您应该使用的(您可以尝试使用填充 DataTable 的 SqlDataAdapter)。

标签: c# asp.net sqldatasource


【解决方案1】:

你可以试试这个方法吗?

                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】:

我遇到了完全相同的问题,终于得到了答案。 在“SelectParameters.Add()”方法中声明参数时,只需不插入“@”符号即可。因此,您所要做的就是更改以下行:

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

到:

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

希望这会有所帮助。

【讨论】:

    【解决方案3】:

    我同意@kumbaya。 面临同样的问题。删除了@,它工作正常。

    第 4 行的代码应编辑为

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

    【讨论】:

      猜你喜欢
      • 2011-09-06
      • 2020-02-12
      • 2015-11-20
      • 1970-01-01
      • 1970-01-01
      • 2011-10-08
      • 1970-01-01
      • 2012-01-12
      • 1970-01-01
      相关资源
      最近更新 更多