建立一个窗体应用。
- using System;
- using System.Collections.Generic;
- using System.ComponentModel;
- using System.Data;
- using System.Drawing;
- using System.Linq;
- using System.Text;
- using System.Windows.Forms;
- using System.Data.SqlClient;
- namespace wjj
- {
- public partial class Form1 : Form
- {
- string conStr = @"Data Source=.\SQLEXPRESS;Initial Catalog=TestDB;Integrated Security=True;";
- string selStr = @"select No,Name,XB,Grade,JG from JBQK";
- SqlConnection sqlCon;
- SqlDataAdapter sda;
- DataSet ds;
- DataTable dt;
- public Form1()
- {
- InitializeComponent();
- }
- private void Form1_Load(object sender, EventArgs e)
- {
- // TODO: 这行代码将数据加载到表“testDBDataSet.JBQK”中。您可以根据需要移动或删除它。
- this.jBQKTableAdapter.Fill(this.testDBDataSet.JBQK);
- }
- private void button1_Click(object sender, EventArgs e)
- {
- sqlCon = new SqlConnection(conStr);
- sda = new SqlDataAdapter(selStr, conStr);
- ds = new DataSet();
- sda.Fill(ds, "JBQK"); //填充数据集,实质是填充ds中的第0个表
- dt = ds.Tables["JBQK"];
- dataGridView1.DataSource = dt; //将JBQK表的信息绑定到控件dataGridView
- }
- private void button2_Click(object sender, EventArgs e)
- {
- //将DataSet所做的更改与关联的SQL Server数据库的更改相协调
- SqlCommandBuilder scb = new SqlCommandBuilder(sda);
- DialogResult result; //信息框的返回值
- result = MessageBox.Show("确定保存修改过的数据吗??","操作提示",MessageBoxButtons.OKCancel,MessageBoxIcon.Question);
- if (result == DialogResult.OK) {
- dt = ds.Tables["JBQK"];
- sda.Update(dt); //更新数据库
- dt.AcceptChanges(); //接受更新
- }
- }
- private void button3_Click(object sender, EventArgs e)
- {
- Application.Exit();
- }
- }
- }