【问题标题】:Passing parameter to stored procedure from ASP.NET WinForm从 ASP.NET WinForm 向存储过程传递参数
【发布时间】:2016-12-05 09:44:30
【问题描述】:

我在将参数传递给存储过程时遇到问题。没有抛出错误,但无法获得所需的输出。 .cs 是:

private void btnSubmit_Click(object sender, EventArgs e)
{
    try
    {
        if (cbRegions.SelectedIndex > 0)
        {
            con = new SqlConnection(connectionString);
            cmd = new SqlCommand("dbo.SectionIncharge", con);
            cmd.Parameters.Add("@RegionName", SqlDbType.VarChar, 50).Value = cbRegions.SelectedItem.ToString();
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Connection = con;
            con.Open();
            DataTable table = new DataTable();
            table.Load(cmd.ExecuteReader());
            dgvResults.DataSource = table;
            con.Close();
        }
    }
    catch
    {

    }
}

.sql 是:

ALTER PROCEDURE [dbo].[SectionIncharge] @RegionName varchar(50)  --name
AS
select UserName
from SystemUser 
where Description LIKE 'RD OFFICE ' + @RegionName  AND
Enable = 'Y'
GO

我已经仔细检查了存储过程在 SQL Server Management Studio 中是否正常工作,但是当我尝试从 WinForm 调用它时,没有输出。有人可以帮忙吗。谢谢

【问题讨论】:

  • 如果在 SSMS 中调用存储过程没问题,那么问题出在 C# 代码上,而不是 db 代码上。
  • 有人已经向你指出了 ExecuteNonQuery...另外,如果你使用 LIKE,也许你想在 proc 中将一个 '%' 连接到你的参数值

标签: c# .net sql-server stored-procedures


【解决方案1】:

方法ExecuteNonQuery(从名字就可以猜到)只是执行查询,并没有从服务器接收任何输出。

因此,您需要获得您选择的结果 - 您必须使用 ExecuteReader 方法并处理它返回的结果(参见我链接的 MSDN 页面底部的示例)。

或者,如果您使用数据表作为网格的源 - 您可以使用 SqlDataAdapter 类和 Fill 方法来填充这样的数据表。

【讨论】:

  • 我已经更新了代码,但无济于事。调试时,光标从con = new SqlConnection("connectionString"); 行跳转到catch 语句。
  • @RehanKhan 如果您将异常处理代码从 catch 更改为 catch (Exception exc) - 您将能够在调试时收到异常消息。可能是您的连接字符串有问题。
  • 是的,我这样做是为了查看 InnerException 消息,它说:字符串不是 JSON 格式的。初始化字符串的格式不符合从索引 0 开始的规范。"
  • con = new SqlConnection("connectionString"); 更改为 con = new SqlConnection(connectionString); 并开始提供正确的输出。非常感谢您的帮助。
猜你喜欢
  • 1970-01-01
  • 2012-08-09
  • 1970-01-01
  • 2021-04-02
  • 1970-01-01
  • 2013-10-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多