datagridview 表功能强大,在表格上改动后,可以直接更新至数据库。
private void FrmRegion_Load(object sender, EventArgs e) { sql = " select * from region order by region_id "; //order by region_id dt = DBHelper.ExecuteQuery(sql); dataGridView1.DataSource = dt; } private void btnSave_Click(object sender, EventArgs e) { DBHelper.UpdateDataTable(dt, "region"); }
附:DBHelper.cs中的UpdateDataTable()函数代码
public static int UpdateDataTable(DataTable ds, string strTblName) { try { //创建一个用于填充DataSet的对象 cmd = new SqlCommand("SELECT * FROM " + strTblName + " ", conn); SqlDataAdapter myAdapter = new SqlDataAdapter(); //获取SQL语句,用于在数据库中选择记录 myAdapter.SelectCommand = cmd; //自动生成单表命令,用于将对DataSet所做的更改与数据库更改相对应 SqlCommandBuilder myCommandBuilder = new SqlCommandBuilder(myAdapter); return myAdapter.Update(ds); } catch (Exception ex) { MessageBox.Show(ex.Message + "\n 更新失败,错误表名为:" + strTblName); return 0; } finally { conn.Close(); } return 0; }