データグリッドビューでデータを更新するには?
WinFormsでは、DataGridViewのデータを以下の方法で更新できます。
- DataGridViewのデータソースから変更する: DataGridViewのDataSourceプロパティを変更すると、そのデータが更新されます。最初にデータソースをDataGridViewにバインドし、それからデータソースを変更し、最後にDataGridViewのRefreshメソッドでデータを更新します。
dataGridView.DataSource = dataSource; // 将数据源绑定到DataGridView
// 修改数据源
dataSource[index].Property = newValue;
// 刷新DataGridView显示的数据
dataGridView.Refresh();
- DataBindingComplete イベントを使用した DataGridView の更新: データバインディング後に、手動で DataGridView のデータを更新することができます。DataBindingComplete イベントでは、DataGridView の Rows コレクションを使用してデータの変更と更新を行うことができます。
private void dataGridView_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
{
// 修改和更新数据
foreach (DataGridViewRow row in dataGridView.Rows)
{
// 获取数据并修改
var data = (DataRowView)row.DataBoundItem;
data["Property"] = newValue;
}
}
- BindingSourceを使用してデータを更新します。これによりBindingSourceを中間層として、データ ソースとDataGridView間のバインド関係を管理できます。BindingSourceのデータを変更し、次にResetBindingsメソッドを呼び出すことでDataGridViewの表示を更新できます。
BindingSource bindingSource = new BindingSource();
bindingSource.DataSource = dataSource; // 设置数据源
dataGridView.DataSource = bindingSource; // 绑定BindingSource到DataGridView
// 修改BindingSource的数据
bindingSource[index].Property = newValue;
// 更新DataGridView的显示
bindingSource.ResetBindings(false);