将实体绑定到datagridview并允许编辑和删除

时间:2013-06-28 16:37:04

标签: c# linq datagridview

我有一个datagridview,我想将linq查询绑定到它。

这是我班级的水平:

   private readonly SuburbanPortalEntities _entities;
   private List<PaymentType> _paymentTypes;

以下是我的负载中的代码:

  _paymentTypes = (from pt in _entities.PaymentTypes
            where pt.CorporationId.Equals(_currentcorp.CorporationId)
            select pt).ToList();
  dataGridView_PaymentTypes.DataSource = _paymentTypes;

这是我的插入,在这一点上,什么都不做:

private void button_Insert_Click(object sender, EventArgs e)
{
  var row = new PaymentType();
  row.IsActive = false;
  row.IsAdded = true;
  row.CorporationId = _currentcorp.CorporationId;
  row.TokenId = _token.TokenId;
  row.PaymentTypeId = Guid.NewGuid();
  row.ExcludeCreditCodes = 9;
  _paymentTypes.Add(row);
}

我的简单保存按钮:

_entities.SaveChanges();

正在处理现有记录。当我对它们进行更改时,它会更改数据库中的数据。它不适用于新记录,我没有删除,因为我不知道该怎么做。

我更愿意允许datagridview在行上添加记录而不是按钮。此外,通过删除,允许datagridview处理删除。

有什么建议吗?

1 个答案:

答案 0 :(得分:0)

将新数据插入sql server,你可以试试这个:

private void button_Insert_Click(object sender, EventArgs e)
{
  var row = new PaymentType();
  row.IsActive = false;
  row.IsAdded = true;
  row.CorporationId = _currentcorp.CorporationId;
  row.TokenId = _token.TokenId;
  row.PaymentTypeId = Guid.NewGuid();
  row.ExcludeCreditCodes = 9;
  _entities.PaymentTypes.Add(row);  //for linq to sql, you should use InsertOnSubmit()
  _entities.SaveChanges();
}