DataSet,DataGridView的相关操作

using System;
using System.Data;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace DataGrid实验2
{
    public partial class Form1 : Form
    {
        public SqlDataAdapter da;
        public DataSet ds;
        public DataTable dt;
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            Datasetsyan();
            //dataGridView1.Rows.Add();

        }
        public void Datasetsyan()
        {
            string connString = @"
            server = localhost;
            integrated security = true;
            database = student
         ";

            // query
            string sql = @"
            select
               studentID,
               studentName,
               studentSex
            from
               stu
         ";

            // create connection
            SqlConnection conn = new SqlConnection(connString);

            try
            {
                // open connection
                conn.Open();

                // create data adapter
                da = new SqlDataAdapter(sql, conn);
                // create dataset

                ds = new DataSet();
                // fill dataset
                da.Fill(ds);//, "stu"

                // get data table
                dt = ds.Tables[0];//"stu"

            }
            catch (Exception e)
            { MessageBox.Show(e.ToString()); }
            finally
            { 
                conn.Close();
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            dataGridView1.DataSource = dt;                            //数据源绑定
        }

        private void button2_Click(object sender, EventArgs e)
        {
           
            SqlCommandBuilder myCommandBuilder = new SqlCommandBuilder(da);
            da.UpdateCommand = myCommandBuilder.GetUpdateCommand();            //更新数据库
            da.Update(ds);
        }

        private void button3_Click(object sender, EventArgs e)
        {
            dataGridView1.Rows.Remove(dataGridView1.CurrentRow);        // 移除当前行
        }

        private void button4_Click(object sender, EventArgs e)
        {
            dataGridView1.Rows[dataGridView1.Rows.Count - 2].Cells[0].Value= textBox1.Text;
            dataGridView1.Rows[dataGridView1.Rows.Count - 2].Cells[1].Value = textBox2.Text;  //添加行
            dataGridView1.Rows[dataGridView1.Rows.Count - 2].Cells[2].Value = textBox3.Text;
        }
    }
}
实验结果:可以对DataGridView的数据进行删除,添加,并保存到数据库
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值