using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using myClass_LinkDataBase; using System.Data.SqlClient; namespace VA12._DataGridView保存数据 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } public DataTable DT = new DataTable(); public SqlDataAdapter SDA = new SqlDataAdapter(); public SqlCommandBuilder SCB; private void Form1_Load(object sender, EventArgs e) { SqlConnection conn = new SqlConnection("Server=H6;user=sa;pwd=123123;database=2016-04-22"); SqlCommand SCD = new SqlCommand("select top 16 * from [N-基本资料单头] where 员工类别='在职人员' ", 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 (System.Exception ex) { MessageBox.Show(ex.ToString()); return; } MessageBox.Show("更新成功!"); SqlConnection conn = new SqlConnection("Server=H6;user=sa;pwd=123123;database=2016-04-22"); SqlCommand SCD = new SqlCommand("select top 16 * from [N-基本资料单头] where 员工类别='在职人员' ", conn); SDA.SelectCommand = SCD; DT.Clear(); SDA.Fill(DT); bindingSource1.DataSource = DT; bindingNavigator1.BindingSource = bindingSource1; dataGridView1.DataSource = bindingSource1; dataGridView1.RowsDefaultCellStyle.BackColor = Color.White; //背景色 dataGridView1.AlternatingRowsDefaultCellStyle.BackColor = System.Drawing.Color.FromArgb(176, 224, 230); //奇数行颜色 } private void button2_Click(object sender, EventArgs e) { dataGridView1.Rows.RemoveAt(dataGridView1.CurrentCell.RowIndex); SCB=new SqlCommandBuilder (SDA); SDA.Update(DT); MessageBox.Show("删除成功!"); } SqlConnection conn; SqlDataAdapter myda; DataSet myds; DataTable mydt; private void button3_Click(object sender, EventArgs e) { //conn = new SqlConnection("Server=H6;user=sa;pwd=123123;database=2016-04-22"); myda = new SqlDataAdapter("select top 16 * from [N-基本资料单头] where 员工类别='在职人员' ", conn);//数据适配 myds = new DataSet(); myda.Fill(myds, "myTable001"); mydt = myds.Tables[0]; dataGridView1.DataSource = mydt; //conn = new SqlConnection("Server=H6;user=sa;pwd=123123;database=2016-04-22"); //conn.Open(); //SqlCommand com = new SqlCommand("select top 16 * from [N-基本资料单头] where 员工类别='在职人员' ", conn); //SqlDataReader dr = com.ExecuteReader(); //BindingSource bs = new BindingSource(); //bs.DataSource = dr; //this.dataGridView1.DataSource = bs; } private void button4_Click(object sender, EventArgs e) { try { SqlCommandBuilder SCB = new SqlCommandBuilder(myda); myda.Update(myds, "myTable001"); } catch (System.Exception ex) { MessageBox.Show(ex.ToString()); return; } } private void button5_Click(object sender, EventArgs e) { myds.Tables["myTable001"].Clear(); myda.Fill(myds, "myTable001"); } private void button6_Click(object sender, EventArgs e) { DataRow row = mydt.NewRow(); row["员工代号"] = "XXXX"; mydt.Rows.Add(row); } } } |
|
来自: 时间剧毒 > 《第十五章:表格数据控件》