DataSet用法

来源:互联网 发布:linux rm命令详解 编辑:程序博客网 时间:2024/05/29 18:11

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace Test
{
    public partial class Form2 : Form
    {
        public Form2()
        {
            InitializeComponent();
        }

       
        DataTable dt;
        DataSet ds;
        SqlConnection conn;
        SqlDataAdapter da;
        private void Form2_Load(object sender, EventArgs e)
        {
            conn = new SqlConnection("Data Source=xsd001;User ID=sa;Password=sa;Initial Catalog=Test;");
            ds=new DataSet();
            da = new SqlDataAdapter("select * from table1", conn);
            SqlCommandBuilder cmd = new SqlCommandBuilder(da);

            da.FillSchema(ds, SchemaType.Source);
            da.Fill(ds);
            dt = new DataTable();
            dt = ds.Tables[0];
            dataGridView1.DataSource = dt;
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            da.Update(ds);
            this.label3.Text = "操作状态:数据保存成功!";
            this.timer1.Start();
        }

        private void btnLoad_Click(object sender, EventArgs e)
        {
            this.Form2_Load(null, null);
           
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            DataRow dr = dt.NewRow();
            dr[1] = this.textBox1.Text;
            dr[2] = this.textBox2.Text;
            dt.Rows.Add(dr);
            this.label3.Text = "操作状态:添加成功,请保存数据!";
            this.timer1.Start();
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            this.label3.Text = "操作状态:..";
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            int d=Int32.Parse(this.textBox1.Text);
            DataRow dr = dt.Rows.Find(d);
            dr.Delete();
            this.label3.Text = "操作状态:删除成功,请保存数据!";
        }
    }
}