0

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

数据库包含列:1. Id、2. Ticker、3. Shares、4. ProfitLoss、5. TradePrice、6. CurrentPrice 和 7. TotalValue

所以基本上我点击购买,然后它插入一个新行。如果我再次单击 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);
                }
            }
        }
    }
4

0 回答 0