日期:2014-05-18 浏览次数:21044 次
public partial class DGVUpdateDB : Form { private DataTable dt = new DataTable(); private SqlDataAdapter sda = new SqlDataAdapter(); public DGVUpdateDB() { InitializeComponent(); this.dataGridView1.DataError += delegate(object sender, DataGridViewDataErrorEventArgs e) { }; dataList_FieldType dFieldType = new dataList_FieldType(); Name.DataPropertyName = "name"; age.DataPropertyName = "age"; serid.DataPropertyName = "serid"; FieldType.DataSource = dFieldType; FieldType.ValueMember = "nFieldType"; FieldType.DisplayMember = "sFieldType"; FieldType.DataPropertyName = "nFieldType"; } private void DGVUpdateDB_Load(object sender, EventArgs e) { SqlConnection conn = new SqlConnection("server=127.0.0.1;database=Test_DB;uid=sa;pwd=123456"); SqlCommand scd = new SqlCommand("select name,age,serid,nFieldType from tUser", conn); sda.SelectCommand = scd; sda.Fill(dt); dataGridView1.DataSource = dt; } //更新数据库 private void button1_Click(object sender, EventArgs e) { try { SqlCommandBuilder scb = new SqlCommandBuilder(sda); sda.Update(dt); } catch (Exception ex) { MessageBox.Show(ex.Message); return; } MessageBox.Show("更新成功!"); } } //下拉框内容 class dataList_FieldType : DataTable { public DataColumn nFieldType = null; public DataColumn sFieldType = null; public dataList_FieldType() { //为DataTable定义两列 nFieldType = new DataColumn(); sFieldType = new DataColumn(); nFieldType.ColumnName = "nFieldType"; sFieldType.ColumnName = "sFieldType"; nFieldType.DataType = typeof(int); sFieldType.DataType = typeof(string); //将列加入到DataTable this.Columns.Add(nFieldType); this.Columns.Add(sFieldType); DataRow dr = this.NewRow(); dr["nFieldType"] = 1; dr["sFieldType"] = "1.Integer"; this.Rows.Add(dr); dr = this.NewRow(); dr["nFieldType"] = 2; dr["sFieldType"] = "2.numeric"; this.Rows.Add(dr); dr = this.NewRow(); dr["nFieldType"] = 3; dr["sFieldType"] = "3.varchar"; this.Rows.Add(dr); dr = this.NewRow(); dr["nFieldType"] = 4; dr["sFieldType"] = "4.datetime"; this.Rows.Add(dr); }