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

How do i display a select stored procedure result in a textbox?

我需要将存储过程中 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;
        }

        }

它给我一个"Procedure NewCID has no parameters and arguments were supplied."错误

您没有执行指定的程序。该过程被命名为 yadayada您可以给出的最糟糕的名称)并且您正在执行过程 NewCustomer 作为命令文本。两者必须相同。那么您正在使用错误的语句来执行查询。

The ExecuteNonQuery to perform catalog operations (for example, querying the structure of a database or creating database objects such as tables), or to change the data in a database without using a DataSet by executing UPDATE, INSERT, or DELETE statements.

但是您正在使用它来执行 select 查询。在这里,您 select 从 table 获取单个值,因此 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(); 
 }