简体   繁体   中英

Can't add more than one row to DataSet

Here's the code:

DataSet1.CashRow CashRow = MainDataSet.Cash.NewCashRow();
CashRow.SetIdNull();
CashRow.Date = CashItem.Date;
CashRow.Description = CashItem.Description;
CashRow.Amount = CashItem.Amount;
MainDataSet.Cash.Rows.Add(CashRow);

It works just fine for the first time. However, if put in a cycle and simply doubled, no more rows are added. I have to close application and start it again.

Update: I have a DataGridView which is connected to the DataSet. Could this cause any problems? This issue is really weird, been trying to fix this for a week now. Maybe there are another ways to add rows?

Update 2: found the cause: "System.Data.ConstraintException: Column 'Id' is constrained to be unique. Value '' is already present.".

try this:

DataSet1.CashRow CashRow = MainDataSet.Cash.NewCashRow();
CashRow.Date = CashItem.Date;
CashRow.Description = CashItem.Description;
CashRow.Amount = CashItem.Amount;

MainDataSet.Cash.AddCashRow(CashRow);

CashTableAdapter.Update(MainDataSet);

And if it still update only one row put this block as function, like this:

private void CreateCashRow (DateTime date, string description, int amount)
{
   DataSet1.CashRow CashRow = MainDataSet.Cash.NewCashRow();
   CashRow.Date = date;
   CashRow.Description = description;
   CashRow.Amount = amount;

   MainDataSet.Cash.AddCashRow(CashRow);

   CashTableAdapter.Update(MainDataSet);
}

And call the function as many time you need.

You must make sure you have PrimaryKey on the table

  • I also suggest to you not to use so similar names for vars and types like you did with the CashRow.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM