2016-05-13 49 views
1

我想在每次點擊按鈕時將新行添加到gridcontrol。我嘗試了很多方法,但沒有成功。我正在發送我的代碼。如何在每次點擊時向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); 
    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(); 
} 
+1

首先你在我的第一個問題中使用我的代碼http://stackoverflow.com/questions/37187344/how-can-i-add-a-new-row-to-datagrid-at-every-button-click -in-winform –

+0

在gridControl1.DataSource = dt之後添加gridControl1.DataBind() – Mainak

+0

您必須更改gridControl1.DataSource = dt;到gridView1.DataSource = dt;試試吧 –

回答

0

你得叫

gridView1.DataBind(); 

後你設置DataSource

+0

Devexpress網格不允許DataBind,因此它不可行。 –

0

您可以使用下面的代碼在你的GridControl添加新行:

gridView1.AddNewRow(); 

int rowHandle = gridView1.GetRowHandle(gridView1.DataRowCount); 
if (gridView1.IsNewItemRow(rowHandle)) 
{ 
    gridView1.SetRowCellValue(rowHandle, gridView1.Columns["ColumnName1"], val1); 
    gridView1.SetRowCellValue(rowHandle, gridView1.Columns["ColumnName2"], val2); 
    gridView1.SetRowCellValue(rowHandle, gridView1.Columns["ColumnName3"], val3); 
} 

你必須用您的值更改列名稱和val1,val2,val3。

+0

我已經試過了,這是devexpress解決方案。 –

+0

是的,這是用於devexpress,但是你使用DevExpress的GridControl? –

+0

有問題的代碼有什麼問題?你有錯誤? –

相關問題