jus*_*sij 10
一种方法是这样做:
步骤#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;
Run Code Online (Sandbox Code Playgroud)
步骤#2设置数据适配器SQL命令:
这些SQL命令定义如何通过适配器在网格和数据库之间移动数据.
dataAdapter.DeleteCommand = new SqlCommand(...);
dataAdapter.InsertCommand = new SqlCommand(...);
dataAdapter.UpdateCommand = new SqlCommand(...);
Run Code Online (Sandbox Code Playgroud)
步骤#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();
}
Run Code Online (Sandbox Code Playgroud)
步骤#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();
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7590 次 |
| 最近记录: |