簡體   English   中英

如何在數據綁定時以編程方式向 datagridview 添加一行?

[英]How to programmatically add a row to a datagridview when it is data-bound?

如果綁定到數據源(數據表),如何向 datagridview 控件添加一行? 謝謝!

在數據表中添加一行,datagridview 會自動更新:

DataTable dt = myDataGridView.DataSource as DataTable;
//Create the new row
DataRow row = dt.NewRow();

//Populate the row with data

//Add the row to data table
dt.Rows.Add(row);
  • 創建一個與要在網格中顯示的數據相對應的類(相同的屬性)
  • 在您的數據綁定函數中,獲取您的查詢結果,但將結果放在一個列表中(或任何適合您和數據綁定的 IEnumerable)
  • 根據您的需要創建另一個對象並將其添加到您的列表中
  • 綁定列表

// 我操作了一個綁定列表。 在這里,我按順序向下移動一行。

BindingList<MyType> lst = (BindingList<MyType>)DataGridView.DataSource;
MyType objQcc = lst[rowIndex];
lst.Insert(rowIndex + 2, objQcc);
lst.RemoveAt(rowIndex);        

如果我嘗試將行添加到 datagridview 本身,我使用數據集將行添加到 datagridview,它說它不會因為它的數據綁定而以編程方式添加行。

// 在Form Load中可以找到datagridview的DataSet

advokathusetDataSet.Kunde.Rows.Add(DeletedRowsList[lastindex].Cells[0].Value, DeletedRowsList[lastindex].Cells[1].Value, DeletedRowsList[lastindex].Cells[2].Value, DeletedRowsList[lastindex].Cells[3].Value, DeletedRowsList[lastindex].Cells[4].Value, DeletedRowsList[lastindex].Cells[5].Value, DeletedRowsList[lastindex].Cells[6].Value);

// 從 Datagridview 添加行到列表和從列表添加行到 datagridview - 如何使用列表向 datagridview 添加行

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM