C#-使用数据适配器从数据库中删除行,并用新信息更新它

C#-使用数据适配器从数据库中删除行,并用新信息更新它,c#,database,visual-studio-2015,dataadapter,adapt,C#,Database,Visual Studio 2015,Dataadapter,Adapt,我有一个数据库,存储我当前的股票投资组合(又名仓位),我希望它在每次购买时更新 数据库包含列:1。身份证,2。股票代码,3。股票,4。ProfitLoss,5。贸易价格,6。当前价格,以及7。总价值 所以基本上我点击BUY,然后它插入一个新行。 如果我再次单击BUY,它将不会删除该行,因此不会使用新的行更新该行,因为索引主Id仍然存在 这就是我得到的错误: An unhandled exception of type 'System.Data.SqlClient.SqlException' oc

我有一个数据库,存储我当前的股票投资组合(又名仓位),我希望它在每次购买时更新

数据库包含列:1。身份证,2。股票代码,3。股票,4。ProfitLoss,5。贸易价格,6。当前价格,以及7。总价值

所以基本上我点击BUY,然后它插入一个新行。 如果我再次单击BUY,它将不会删除该行,因此不会使用新的行更新该行,因为索引主Id仍然存在

这就是我得到的错误:

An unhandled exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll

Additional information: Violation of PRIMARY KEY constraint 'PK__tmp_ms_x__3214EC072159A622'. Cannot insert duplicate key in object 'dbo.Table'. The duplicate key value is (0).

The statement has been terminated.
我做错了什么? 坚持了好几个小时。 谢谢 下面是我的代码:

// create Positions database
PositionDBDataSetTableAdapters.TableTableAdapter Position_table_adaptor = new PositionDBDataSetTableAdapters.TableTableAdapter();

private void btnBuyToOpen_Click(object sender, EventArgs e)
    {
        // declare variables
        int shares = (int)nudShares.Value;
        decimal commission = 5;
        decimal cost = 0;
        string menuItem = menuSymbol.SelectedItem.ToString();

        // update buying power
        // and purchase and update Positions database
        if (menuItem == "JERO")
        {
            cost = (JERO.Price * shares) + commission;

            // If user has enough buying power,
            // update the buying power,
            // and update positions database.
            if (updateBuyingPower(cost))
            {
                if (Position_table_adaptor.GetData().Select("Ticker = 'JERO'").Length != 0)
                {
                    Position_table_adaptor.GetData().Rows.Find(0).Delete();
                    Position_table_adaptor.Insert(0, "JERO", shares, 0, JERO.Price, JERO.Price, cost - commission);
                }
                else
                {
                    Position_table_adaptor.Insert(0, "JERO", shares, 0, JERO.Price, JERO.Price, cost - commission);
                }
            }
        }
    }

上传的代码充满了自定义方法,所以你必须自己调试。@LeiYang抱歉,刚刚在顶部添加了适配器位。也许这有助于澄清问题。如果是适配器,用后缀adapter命名变量就好了。@LeiYang好的,我猜你应该调用
adapter.Update
(所以在删除后实际执行sql)。