带有标识列的C#DataGridView

时间:2013-06-20 13:33:35

标签: c# datagridview sql-server-express

我使用Visual Studio 2010,语言C#和SQL Server Express Edition作为后端。有一个带DataGridView控件的表单,我使用designer手动设置列,然后在运行时设置数据源。

connectionString = ConfigurationManager.AppSettings["connectionString"];
sqlConnection = new SqlConnection(connectionString);
sqlConnection.Open();
String sqlSelectDet = "Select OrdDetID, OrderID, ProductID, UnitPrice, Quantity from OrderDetails"; 

//===============================================================================
//--- Set up the INSERT Command OrderDetails
//===============================================================================

sDetInsProcName = "prInsert_OrderDetail";
insertcommandDet = new SqlCommand(sDetInsProcName, sqlConnection);
insertcommandDet.CommandType = CommandType.StoredProcedure;

insertcommandDet.Parameters.Add("@nNewDetID", SqlDbType.Int, 4, "OrdDetID");
insertcommandDet.Parameters.Add("@nOrderID", SqlDbType.Int, 4, "OrderID");
insertcommandDet.Parameters.Add("@nProductID", SqlDbType.Int, 4, "ProductID");
insertcommandDet.Parameters.Add("@mUnitPrice", SqlDbType.Money, 8, "UnitPrice");
insertcommandDet.Parameters.Add("@nQuantity", SqlDbType.SmallInt, 2, "Quantity");

sqlDataDet.InsertCommand = insertcommandDet;

如上所述,我使用的是存储过程prInsert_OrderDetailOrdDetID是一种LineItem编号,它是数据库中的自动增量字段。

为了设置DataGridView,我使用以下内容:

dtDet = new DataTable();
dtDet.Clear(); 
sqlDataDet.FillSchema(dtDet, SchemaType.Source);

ds = new DataSet();
ds.Tables.Add(dtDet);

ds.Tables[1].Columns["OrdDetID"].AutoIncrement = true;
ds.Tables[1].Columns["OrdDetID"].AutoIncrementSeed = -1;
ds.Tables[1].Columns["OrdDetID"].AutoIncrementStep = -1;

bsDet = new BindingSource();
bsDet.DataSource = ds;
bsDet.DataMember = "OrderDetails"; 

// Name of DataGridView Control is dgInvDet
dgInvDet.AutoGenerateColumns = false;
dgInvDet.DataSource = bsDet;
dgInvDet.Columns["OrdDetID"].DataPropertyName = "OrdDetID";
dgInvDet.Columns["OrderID"].DataPropertyName = "OrderID";
dgInvDet.Columns["ProductID"].DataPropertyName = "ProductID";
dgInvDet.Columns["UnitPrice"].DataPropertyName = "UnitPrice";
dgInvDet.Columns["Quantity"].DataPropertyName = "Quantity";

在“保存”按钮单击事件中,以下代码用于将数据从DataGridView保存到数据库:

sqlDataDet.Update(ds.Tables[0]);

SQL Server中的存储过程是:

ALTER  PROCEDURE [dbo].[prInsert_OrderDetail]
@nOrderID INT, 
@nProductID INT, 
@mUnitPrice MONEY, 
@nQuantity SMALLINT,
@nNewDetID INT OUTPUT
AS 
INSERT INTO [OrderDetails] (OrderID, ProductID, UnitPrice, Quantity)
VALUES (@nOrderID, @nProductID, @mUnitPrice, @nQuantity)

    SET @nNewDetID = SCOPE_IDENTITY()

数据正确保存在数据库中,我的问题是如何获得OrdDetID实际身份值,dataGridView在数据库中插入记录后不显示DataGridView中的实际值。因为列的设置,我得到的是-1,-2,-3等等。

有任何想法/建议吗?

由于

艾哈迈德

1 个答案:

答案 0 :(得分:1)

此参数

insertcommandDet.Parameters.Add("@nNewDetID", SqlDbType.Int, 4, "OrdDetID");

需要指定为 ParameterDirection.Output ,例如以下代码行:

    SqlParameter pID = new SqlParameter("nNewDetID", DBType.Int32, 4);
    pID.Direction = ParameterDirection.Output;
    insertcommandDet.Parameters.Add(pID);
    //** other code here...
    insertcommandDet.ExecuteScalar();

执行命令后,通过

提取值
int id = Convert.ToInt32(cmd.Parameters["nNewDetID"].Value.ToString());

您应该能够在控制台应用程序中对此进行测试,以帮助您... ...

            // set connection
            SqlConnection sqlConnection = new SqlConnection("[Your connection string here]");

            // open connection
            sqlConnection.Open();

            // specify the stored procedure which has an output parameter, namely "NewId"
            SqlCommand insertcommandDet = new SqlCommand("[dbo].[TestingSP]", sqlConnection);

            // tell the command that it is a stored procedure
            insertcommandDet.CommandType = CommandType.StoredProcedure;

            // add the parameter having the name
            insertcommandDet.Parameters.AddWithValue("Name","Test Name"); 

            // this parameter will contain the new id after
            SqlParameter pID = new SqlParameter("NewId", SqlDbType.Int, 4);
            pID.Direction = ParameterDirection.Output;

            // add the parameter to the command
            insertcommandDet.Parameters.Add(pID);

            // execute command with ExecuteScalar()
            insertcommandDet.ExecuteScalar();

            // Get parameter value extracted with ExecuteScalar
            int id = Convert.ToInt32(insertcommandDet.Parameters["NewId"].Value.ToString());

我使用的程序如下

create  PROCEDURE [dbo].[TestingSP](
@Name varchar(50) ,
@NewId INT OUTPUT)
AS 
INSERT INTO [Testing]
select @name
    SET @NewId = SCOPE_IDENTITY()