我正在使用以下代码创建数据应用程序 - 但是 我收到了#34;客户ID未被退回。无法创建帐户。"不断。你知道为什么应用程序没有自动创建ID吗?
namespace SmallDataApplication27._08
{
public partial class NewCustomer : Form
{
//NC-2 Storage for IDENTITY values returned from database.
private int parsedCustomerID;
private int orderID;
//NC-3 Specify a connection string.
string connstr = SmallDataApplication27._08.Utility.GetConnectionString();
public NewCustomer()
{
InitializeComponent();
}
//NC-4 Create account.
private void btnCreateAccount_Click(object sender, EventArgs e)
{
//NC-5 Set up and run stored procedure only if Customer Name is present.
if (isCustomerName())
{
//NC-6 Create the connection.
SqlConnection conn = new SqlConnection(connstr);
//NC-7 Create a SqlCommand, and identify it as a stored procedure.
SqlCommand cmdNewCustomer = new SqlCommand("Sales.uspNewCustomer", conn);
cmdNewCustomer.CommandType = CommandType.StoredProcedure;
//NC-8 Add input parameter from the stored procedure and specify what to use as its value.
cmdNewCustomer.Parameters.Add(new SqlParameter("@CustomerName", SqlDbType.NVarChar, 40));
cmdNewCustomer.Parameters["@CustomerName"].Value = txtCustomerName.Text;
//NC-9 Add output parameter.
cmdNewCustomer.Parameters.Add(new SqlParameter("@CustomerID", SqlDbType.Int));
cmdNewCustomer.Parameters["@CustomerID"].Direction = ParameterDirection.Output;
//NC-10 try-catch-finally
try
{
//NC-11 Open the connection.
conn.Open();
//NC-12 Run the stored procedure.
cmdNewCustomer.ExecuteNonQuery();
//NC-13 Customer ID is an IDENTITY value from the database.
this.parsedCustomerID = (int)cmdNewCustomer.Parameters["@CustomerID"].Value;
this.txtCustomerID.Text = Convert.ToString(parsedCustomerID);
}
catch
{
//NC-14 A simple catch.
MessageBox.Show("Customer ID was not returned. Account could not be created.");
实用程序文件:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Configuration;
namespace SmallDataApplication27._08
{
internal class Utility
{
internal static string GetConnectionString()
{
//Util-2 Assume failure.
string returnValue = null;
//Util-3 Look for the name in the connectionStrings section.
ConnectionStringSettings settings =
ConfigurationManager.ConnectionStrings["SmallDataApp.Properties.Settings.connString"];
//If found, return the connection string.
if (settings != null)
returnValue = settings.ConnectionString;
return returnValue;
}
}
}