簡體   English   中英

僅返回數據網格視圖的更改行?

[英]Return only the changed rows of a datagridview?

我有一個包含 datagridview 的 winform。 表格與數據完全脫節。 代碼隱藏調用一個 web 服務,它返回一個表。 該表成為數據網格視圖的數據源。 顯示數據網格視圖后,用戶可以編輯任何行。 目前,當他們點擊“更新”按鈕時,網格中的每一行都會被返回。

有沒有辦法只返回 datagridview 中更改的行?

更新:基於下面 Tezzo 的回答,我能夠做到這一點:

var changedRows = ((DataTable)dataGridView1.DataSource).GetChanges(DataRowState.Modified).Rows;

您可以使用GetChanges 檢索 DataTable 更改

因此,您可以將此代碼與DataGridView一起使用:

CType(YourDataGridView.DataSource, DataTable).GetChanges(DataRowState.Modified).Rows

我在C#中提出了一個可行的解決方案,其中我考慮用戶編輯當前單元格然后執行保存/更新而不移出已編輯的行。 由於其RowState仍被標記為“未Unchanged ”,因此對GetChanges()的調用將無法識別當前編輯的行。 如果用戶停留在正在編輯的當前單元格上,我也會調用移動到下一行,因為GetChange()不會觸及最后編輯的單元格。

//Move to previous cell of current edited row in case user did not move from last edited cell
dgvMyDataGridView.CurrentCell = dgvMyDataGridView.Rows[dgvMyDataGridView.CurrentCell.RowIndex].Cells[dgvMyDataGridView.CurrentCell.ColumnIndex - 1];

//Attempts to end the current edit of dgvMyDataGridView for row being edited
BindingContext[dgvMyDataGridView.DataSource, dgvMyDataGridView.DataMember.ToString()].EndCurrentEdit();

//Move to next row in case user did not move from last edited row
dgvMyDataGridView.CurrentCell = dgvMyDataGridView.Rows[dgvMyDataGridView.CurrentCell.RowIndex + 1].Cells[0];

//Get all row changes from embedded DataTable of DataGridView's DataSource
DataTable changedRows = ((DataTable)((BindingSource)dgvMyDataGridView.DataSource).DataSource).GetChanges();

foreach (DataRow row in changedRows.Rows)
{
        //row["columnName"].ToString();
        //row[0].ToString();
       //row[1].ToString();
}

這是使用 C# 獲取已在 DataGridView 中修改的所有行的簡單方法:

 DataRowCollection modifiedRows = ((DataTable)YourGridView.DataSource).GetChanges(DataRowState.Modified).Rows;

暫無
暫無

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

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