winfrom增删改查

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

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            //dataGridView不自动为我们生成列
            dataGridView1.AutoGenerateColumns = false;
        }
        string connStr = "server=DESKTOP-QQGOIKH;uid=sa;pwd=123;database=stuDB";
        private void Form1_Load(object sender, EventArgs e)
        {
            BindList();

        }

        private void BindList()
        {
            string sql = "select * from student";
            SqlConnection conn = new SqlConnection(connStr);
            conn.Open();
            SqlCommand cmd = new SqlCommand(sql, conn);
            SqlDataAdapter sda = new SqlDataAdapter(cmd);
            DataSet ds = new DataSet();
            sda.Fill(ds, "aa");
            conn.Close();
            DataTable dt = ds.Tables["aa"];
            dataGridView1.DataSource = dt;
        }

        private void groupBox1_Enter(object sender, EventArgs e)
        {

        }

        private void button1_Click(object sender, EventArgs e)
        {
            //取数据
            string stuName = textBox1.Text;
            string stuNo = textBox2.Text;
            string sex = "女";
            if (radioButton1.Checked)
            {
                sex = "男";
            }
            string remark = richTextBox1.Text;
            //2准备sql语句与参数
            string sql = "insert into student values(@a,@b,@c,@d)";
            SqlParameter[] pms = new SqlParameter[4];
            pms[0] = new SqlParameter("@a",stuName);
            pms[1] = new SqlParameter("@b", stuNo);
            pms[2] = new SqlParameter("@c",sex);
            pms[3] = new SqlParameter("@d", remark);
            //3,Ado.net
            SqlConnection conn = new SqlConnection(connStr);
            conn.Open();
            SqlCommand cmd = new SqlCommand(sql,conn);
            cmd.Parameters.AddRange(pms);
            int i= cmd.ExecuteNonQuery();
            conn.Close();
            //四,判断结果
            if (i>0)
            {
                MessageBox.Show("新增成功");
                BindList();
            }
            else
            {
                MessageBox.Show("新增失败");
            }
        }
    }
}

  

你可能感兴趣的:(winfrom增删改查)