如何在文本框中显示选择的存储过程结果?

时间:2016-08-26 07:49:46

标签: c# sql ado.net

我需要将存储过程中select语句的结果显示在文本框中,我无法弄清楚如何操作。 select语句不使用WHERE子句。存储过程

CREATE PROCEDURE NewCustomer
AS
BEGIN
SELECT MAX(ID) + 1 FROM Database
END

这就是我试过的

protected void btnNew_Click(object sender, EventArgs e)
    {
        Clear();
        int num;

        try
        {
            using (SqlCommand command = new SqlCommand("NewCustomer"))
            {
                command.Connection = conn;
                command.CommandType = CommandType.StoredProcedure;
                command.Parameters.Add("@CustID", SqlDbType.Int).Value = Int32.TryParse(txtCID.Text, out num); // Use tryparse if needed
                conn.Open();
                txtCID.Text = (string)command.ExecuteScalar();
            }
        }
        catch (Exception ex)
        {
            lblMessage.Text = ex.Message;
        }

        }

它给了我一个“过程NewCID没有提供参数和参数。”错误

1 个答案:

答案 0 :(得分:1)

您没有执行您提供的程序。该过程命名为yadayada您可以提供的最差名称),并且您正在执行过程NewCustomer作为命令文本。两者都必须相同。然后,您使用错误语句来执行查询。

  

ExecuteNonQuery执行目录操作(例如,   查询数据库的结构或创建数据库对象   如表),或更改数据库中的数据而不使用   通过执行UPDATE,INSERT或DELETE语句来实现DataSet。

但是您正在使用它来执行选择查询。在这里,您从表中选择一个值,因此ExecuteScalar将是您的最佳选择。您的代码将如下所示:假设过程名称为GetNewCustomerID;

 using (SqlCommand exeCommand = new SqlCommand("GetNewCustomerID"))
 {
     exeCommand.Connection = conn;
     exeCommand.CommandType = CommandType.StoredProcedure;
     exeCommand.Parameters.Add("@CustID",SqlDbType.Int).Value=Convert.ToInt32(txtCID.Text); // Use tryparse if needed
     conn.Open();
     txtCID.Text = (string)exeCommand.ExecuteScalar(); 
 }