如何在winform中的每次按钮单击时向datagrid添加新行

时间:2016-05-12 12:46:30

标签: c# winforms entity-framework-6 devexpress

我想在每次点击按钮时向gridcontrol添加新行。 我尝试了很多方法但没有成功。我正在发送我的代码。

private void B_Click(object sender, EventArgs e)
{
   Button bt = (Button)sender;
   int productId = (int)bt.Tag;
   AddProductDataContext db = new AddProductDataContext();
   decimal Quantity;
   decimal.TryParse(txtCalculator.Text, out Quantity);
   gridControl1.DataSource = from inv in db.Inventories where inv.RecId == productId
      select new
      {
         inventoryName = inv.InventoryName,
         Quantity,
         Total = Quantity * inv.InventoryPrice
      };
   gridView1.AddNewRow();
   gridView1.UpdateCurrentRow();
} 

有没有人可以帮我解决上述问题?提前感谢您的宝贵回复。

1 个答案:

答案 0 :(得分:0)

试试这个:

Button bt = (Button)sender;
       int productId = (int)bt.Tag;
       AddProductDataContext db = new AddProductDataContext();
       decimal Quantity;
       decimal.TryParse(txtCalculator.Text, out Quantity);
     var results  = from inv in db.Inventories
                                          where inv.RecId == productId
                                          select new
                                          {
                                              inventoryName = inv.InventoryName,
                                              Quantity,
                                              Total = Quantity * inv.InventoryPrice
                                          };

               DataTable dt = new DataTable();
               dt.Columns.Add("inventoryName");
               dt.Columns.Add("Quantity");
               dt.Columns.Add("Total");

               foreach (var x in results)
               {
                   DataRow newRow = dt.Rows.Add();
                   newRow.SetField("inventoryName", x.inventoryName);
                   newRow.SetField("Quantity", x.Quantity);

                   newRow.SetField("Total", x.Total);

               }

               gridControl1.DataSource = dt;
               gridView1.AddNewRow();