一、winfrom的增删查改都要来自于数据库要有表数据,这对于winfrom做后端的程序员来讲是必不可少的,没有数据是无法执行操作的。
1、设置好控件及属性:
窗体及控件属性设置
窗体和控件 | 属性 | 属性值 |
Button1 | Name Text | btnAdd 增加 |
Button2 | Name Text | btnDelete 删除 |
Button3 | Name Text | btnSelect 查询 |
Button4 | Name Text | btnRevise 修改 |
DataGridView1 | Name | dataGridView1 |
GroupBox1 | Name Text | testGroupBox1 增删查改测试 |
2、我们用到的操作环境是Visual Studio 2020 我选择新建项目选择Window窗体开发(.NET Frmwork) 并在项目名称中定义textFrom,最后选择自已要放的盘
3、设置好自已的窗体并保持美观
特别注意的DataGridView1这个控件要与数据库建的表定义要一致,不然后面的一系列增删查改的代码执行不成功
4、代码展示
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 TestFrom
{
public partial class From1 : Form
{
public From1()
{
InitializeComponent();
}
private void btnbtnAdd_Click(object sender, EventArgs e)
{
//链接数据库创建一个新增
string constr = "Server=120.55.99.16\\MSSQLSERVER,5699;Database=Thefirstgroup;UID=sa;PWD=ZHANGxinfang2004;";
SqlConnection connection = new SqlConnection(constr);
try
{
connection.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = connection;
//创建命令项目
//新增的数据
string sqlstr = "insert into Doctor_Information values('000106','刘得滑','男','18','15674620023','白内障')";
cmd.CommandText = sqlstr;
//4.执行命令
int i = cmd.ExecuteNonQuery();
Text = i.ToString();
}
catch (Exception ex)
{
}
}
private void btnbtnDelete_Click(object sender, EventArgs e)
{
string constr = "Server=120.55.99.16\\MSSQLSERVER,5699;Database=Thefirstgroup;UID=sa;PWD=ZHANGxinfang2004;";
SqlConnection connection = new SqlConnection(constr);
try
{
connection.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = connection;
//创建命令项目
//新增的数据
string sqlstr = "delete from Doctor_Information where idDoctor=000106";
cmd.CommandText = sqlstr;
//4.执行命令
int i = cmd.ExecuteNonQuery();
Text = i.ToString();
}
catch (Exception ex)
{
}
}
private void btnSelect_Click(object sender, EventArgs e)
{
//链接数据库来实现查询 链接外网数据库
SqlConnection conn = new SqlConnection("Server=120.55.99.16\\MSSQLSERVER,5699;Database=Thefirstgroup;UID=sa;PWD=ZHANGxinfang2004");
conn.Open();
SqlCommand cmd = new SqlCommand("select * from Doctor_Information", conn);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
sda.Fill(ds);
DataTable dt = ds.Tables[0];
dataGridView1.AutoGenerateColumns = false;
dataGridView1.DataSource = ds.Tables[0];
conn.Close();
}
private void btnRevise_Click(object sender, EventArgs e)
{
}
}
}
5、最后代码效果图展示: