how can I add a new row to datagrid at every button click in winform

我是研究僧i 提交于 2019-12-12 04:31:58

问题


I want to add new row to gridcontrol at every button click. I tried many ways but no success. I am sending my code.

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();
} 

Is there anyone to help me out for the above? Thanks in advance for your precious replies.


回答1:


Try this :

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();


来源:https://stackoverflow.com/questions/37187344/how-can-i-add-a-new-row-to-datagrid-at-every-button-click-in-winform

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!