DataGirdView 增删改查(一)

新建一个DBconn类:

using System;
using System.Collections.Generic;
using System.Text;
using System.Data.SqlClient;

namespace test
{
  public class DBConn
  {
  public static string connStr  = ConfigurationManager.ConnectionStrings["supermarketConstring"].ToString();//首先获取连接数据库字符串  public static SqlConnection conn = new SqlConnection(connStr);
  }
}



下面是窗体,有两个文本框,txtno,txtname,四个按钮增,删,改,查

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

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

  DataSet ds;
  SqlDataAdapter ada;
  string sql = null;
  SqlCommand cmd;

//查询
  private void btnSearch_Click(object sender, EventArgs e)
  {
  ShowView();
  }

  private void ShowView()
  {
  ds = new DataSet("myschool");
  if (ds.Tables.Count > 0)
  ds.Tables.Clear();
  sql = "SELECT * FROM classinfo";
  ada = new SqlDataAdapter(sql, DBConn.conn);
  ada.Fill(ds);
  this.dataGridView1.DataSource = ds.Tables[0];
  }
//添加
  private void btnAdd_Click(object sender, EventArgs e)
  {
  sql = string.Format("INSERT classInfo VALUES ({0},'{1}')", int.Parse(txtNo.Text), txtName.Text);
  cmd = new SqlCommand(sql, DBConn.conn);
  DBConn.conn.Open();
  int count = cmd.ExecuteNonQuery();
  if (count > 0)
  {
  MessageBox.Show("添加成功!");
  }
  else 
  {
  MessageBox.Show("添加失败!");
  }
  DBConn.conn.Close();
  ShowView();
  }
//删除
  private void btnDelete_Click(object sender, EventArgs e)
  {
  sql = string.Format("delete classinfo WHERE classno = {0}", int.Parse(txtNo.Text));
  cmd = new SqlCommand(sql, DBConn.conn);
  DBConn.conn.Open();
  int count = cmd.ExecuteNonQuery();
  if (count > 0)
  {
  MessageBox.Show("删除成功!");
  }
  else
  {
  MessageBox.Show("删除失败!");
  }
  DBConn.conn.Close();
  ShowView();
  }
//修改
  private void btnUpdate_Click(object sender, EventArgs e)
  {
  SqlCommandBuilder bl = new SqlCommandBuilder(ada);
  ada.Update(ds);
  ShowView();
  }
  }
}

你可能感兴趣的:(职场,增删改查,休闲,DataGirdView)