在为datagridview分配数据源时添加行
时间:2020-03-06 14:34:50 来源:igfitidea点击:
我有一个datagridview为其分配了一个数据源。现在如何在该网格中添加新行并从中删除一行?
解决方案
我相信我们将必须获取Table集合项并从中检索Row集合项。然后,我们可以遍历各行,也可以删除该行。
当然,我们需要在绑定后执行此操作。
一种方法如下:
步骤#1设置数据适配器,数据网格等:
// the data grid DataGridView dataGrid; // create a new data table DataTable table = new DataTable(); // create the data adapter SqlDataAdapter dataAdapter = new SqlDataAdapter(strSQL, strDSN); // populate the table using the SQL adapter dataAdapter.Fill(table); // bind the table to a data source BindingSource dbSource = new BindingSource(); dbSource.DataSource = table; // finally bind the data source to the grid dataGrid.DataSource = dbSource;
步骤#2设置数据适配器SQL命令:
这些SQL命令定义如何通过适配器在网格和数据库之间移动数据。
dataAdapter.DeleteCommand = new SqlCommand(...); dataAdapter.InsertCommand = new SqlCommand(...); dataAdapter.UpdateCommand = new SqlCommand(...);
步骤#3代码,以从数据网格中删除选择的行:
public int DeleteSelectedItems() { int itemsDeleted = 0; int count = dataGrid.RowCount; for (int i = count - 1; i >=0; --i) { DataGridViewRow row = dataGrid.Rows[i]; if (row.Selected == true) { dataGrid.Rows.Remove(row); // count the item deleted ++itemsDeleted; } } // commit the deletes made if (itemsDeleted > 0) Commit(); }
步骤#4处理行插入和行更改:
这些类型的更改相对容易实现,因为我们可以让网格管理单元格更改和新行插入。
我们唯一需要决定的是何时提交这些更改。
我建议将提交放入DataGridView的RowValidated事件处理程序中,因为此时我们应该有完整的数据行。
步骤#5提交方法将更改保存回数据库:
此功能将处理所有待处理的更新,插入和删除,并将这些更改从网格移回到数据库中。
public void Commit() { SqlConnection cn = new SqlConnection(); cn.ConnectionString = "Do the connection using a DSN"; // open the connection cn.Open(); // commit any data changes dataAdapter.DeleteCommand.Connection = cn; dataAdapter.InsertCommand.Connection = cn; dataAdapter.UpdateCommand.Connection = cn; dataAdapter.Update(table); dataAdapter.DeleteCommand.Connection = null; dataAdapter.InsertCommand.Connection = null; dataAdapter.UpdateCommand.Connection = null; // clean up cn.Close(); }
GridView中的"行"属性没有Delete方法,因此我们无法直接删除行。我们必须从数据源中删除项目,而不是重新制作DataBind。我们也可以在该行中将Visibile = false设置为该行,这样它将对用户显示为"已删除"。