蜗牛—C#程设之DataGridView数据库绑定控件

来源:互联网 发布:淘宝切片上传有空隙 编辑:程序博客网 时间:2024/06/06 12:35

建立一个窗体应用。

[csharp] view plaincopy在CODE上查看代码片派生到我的代码片
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.ComponentModel;  
  4. using System.Data;  
  5. using System.Drawing;  
  6. using System.Linq;  
  7. using System.Text;  
  8. using System.Windows.Forms;  
  9. using System.Data.SqlClient;  
  10.   
  11. namespace wjj  
  12. {  
  13.     public partial class Form1 : Form  
  14.     {  
  15.         string conStr = @"Data Source=.\SQLEXPRESS;Initial Catalog=TestDB;Integrated Security=True;";  
  16.         string selStr = @"select No,Name,XB,Grade,JG from JBQK";  
  17.         SqlConnection sqlCon;  
  18.         SqlDataAdapter sda;  
  19.         DataSet ds;  
  20.         DataTable dt;  
  21.         public Form1()  
  22.         {  
  23.             InitializeComponent();  
  24.         }  
  25.   
  26.         private void Form1_Load(object sender, EventArgs e)  
  27.         {  
  28.             // TODO: 这行代码将数据加载到表“testDBDataSet.JBQK”中。您可以根据需要移动或删除它。  
  29.             this.jBQKTableAdapter.Fill(this.testDBDataSet.JBQK);  
  30.   
  31.         }  
  32.   
  33.         private void button1_Click(object sender, EventArgs e)  
  34.         {  
  35.             sqlCon = new SqlConnection(conStr);  
  36.             sda = new SqlDataAdapter(selStr, conStr);  
  37.             ds = new DataSet();  
  38.             sda.Fill(ds, "JBQK");   //填充数据集,实质是填充ds中的第0个表  
  39.             dt = ds.Tables["JBQK"];  
  40.             dataGridView1.DataSource = dt;   //将JBQK表的信息绑定到控件dataGridView  
  41.         }  
  42.   
  43.         private void button2_Click(object sender, EventArgs e)  
  44.         {  
  45.             //将DataSet所做的更改与关联的SQL Server数据库的更改相协调  
  46.             SqlCommandBuilder scb = new SqlCommandBuilder(sda);  
  47.             DialogResult result;        //信息框的返回值  
  48.             result = MessageBox.Show("确定保存修改过的数据吗??","操作提示",MessageBoxButtons.OKCancel,MessageBoxIcon.Question);  
  49.             if (result == DialogResult.OK) {   
  50.                 dt = ds.Tables["JBQK"];  
  51.                 sda.Update(dt);      //更新数据库  
  52.                 dt.AcceptChanges();  //接受更新  
  53.             }  
  54.         }  
  55.   
  56.         private void button3_Click(object sender, EventArgs e)  
  57.         {  
  58.             Application.Exit();  
  59.         }  
  60.     }  
  61. }  
0 0
原创粉丝点击