欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

C#winform窗口登录和数据的增删改查

程序员文章站 2022-04-05 10:27:54
工具:VS2013 数据库SqlServer2008 两张表,一个用户登录表,一个资料表用于增删改查 。先把表建好。可以根据我发的图建立,这样下面的代码修改的就少。 资料部分SQL CREATE TABLE [dbo].[Customer]( [CustomerID] [varchar](20) N ......

工具:vs2013

数据库sqlserver2008

两张表,一个用户登录表,一个资料表用于增删改查 。先把表建好。可以根据我发的图建立,这样下面的代码修改的就少。

C#winform窗口登录和数据的增删改查

C#winform窗口登录和数据的增删改查

资料部分sql

 

create table [dbo].[customer](
[customerid] [varchar](20) not null,
[companyname] [varchar](20) null,
[contacname] [varchar](20) null,
[contactitle] [nchar](10) null,
[address] [nchar](10) null,
[city] [nchar](10) null,
[region] [nchar](10) null,
[postalcode] [nchar](10) null,
[country] [nchar](10) null,
[phone] [nchar](10) null,
[fax] [nchar](10) null,
constraint [pk_customer] primary key clustered
(
[customerid] asc
)with (pad_index = off, statistics_norecompute = off, ignore_dup_key = off, allow_row_locks = on, allow_page_locks = on) on [primary]
) on [primary]

go

set ansi_padding off
go

 

一、新建项目

  C#winform窗口登录和数据的增删改查

二、拖入控件,自己拖入,不用说了。

C#winform窗口登录和数据的增删改查

三、双击登录按钮,在双击方法里面写入下面代码。(form2是登录成功跳转到的页面,顺便新建一个就好了。里面有输入框什么的名称报错,自己修改修改。改成和我一样的就可以了。

最上面加入下面的引用

using system;
using system.collections.generic;
using system.componentmodel;
using system.data;
using system.drawing;
using system.linq;
using system.text;
using system.windows.forms;

 

private void button1_click(object sender, eventargs e)
{
string uername = textbox1.text.trim();
string pwd = textbox2.text;
// 建立sqlconnection对象,根据你的数据库,用户名和密码修改一下
sqlconnection con = new sqlconnection("server=laptop-svlmbjt3;database=northwind;user=sa;pwd=sa");
// 打开连接
con.open();
// 指定sql语句,我是数据库的一张表,用来测试登录,自己建立一个表,
sqlcommand com = new sqlcommand("select username,password from tb_myuser where username='" + uername + "' and password='" + pwd + "'", con);
// 建立sqldataadapter和dataset对象
sqldataadapter da = new sqldataadapter(com);
dataset ds = new dataset();
int n = da.fill(ds, "tb_myuser");
if (n != 0)
{
messagebox.show("登录成功!", "提示");
this.hide();
form2 f2 = new form2();
f2.showdialog();
}
else
{
messagebox.show("用户名或密码错误,请重新输入!", "提示");
textbox1.text = "";
textbox2.text = "";
textbox1.focus();
}
con.close();
}

四、就可以测试登录了,登录成功后就跳转到from2了。下来我们做form2的窗口。

如果前面新建了form2就直接打开,没有的话就新建一个。如下图。一个menustrip按钮,一个combobox下拉,一个textbox,两个按钮,一个datagridview里面有两个按钮,一个删除一个修改

C#winform窗口登录和数据的增删改查

在datagridview1里设置两个按钮,一个删除按钮一个修改按钮,新增用上面那个按钮,点击进入另一个页面新增。

删除按钮

C#winform窗口登录和数据的增删改查

 

 修改按钮

C#winform窗口登录和数据的增删改查

五、双击form2的页面,加入下面代码,加载下拉查询条件。

 

using system;
using system.collections.generic;
using system.componentmodel;
using system.data;
using system.drawing;
using system.linq;
using system.text;
using system.windows.forms;

 

/// <summary>
/// 初始化
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void form2_load(object sender, eventargs e)
{
// 建立sqlconnection对象
//sqlconnection con = new sqlconnection("server=192.168.1.19;database=northwind;user=mistest;pwd=mistest");
sqlconnection con = new sqlconnection("server=laptop-svlmbjt3;database=northwind;user=sa;pwd=sa");
// 打开连接
con.open();
// 指定sql语句 
sqlcommand com = new sqlcommand("select distinct country from customer", con);
// 建立sqldataadapter和dataset对象
sqldatareader sdr = com.executereader();
while (sdr.read())
{
combobox1.items.add(sdr[0].tostring());//循环读取数据
}
sdr.close();// 关闭数据集
}

 六、双击查询,我们来做查询。写入下面的代码

string strsql = "select customerid as id,companyname as 公司名称 ,country as 国家 ,contacname as 联系人 , contactitle as 联系人称呼, address as 地址 ,city as 城市, region as 地区 , postalcode as 邮编 from customer where 1=1";//查询语句。
if (combobox1.text != "")
{
strsql = strsql + " and country = '" + combobox1.text + "' ";
}
if (textbox2.text != "")
{
strsql = strsql + " and companyname like '%" + textbox2.text.toupper() + "%' ";
}
datagridview1.datasource = utils.getdataset(strsql);
this.datagridview1.columns["cz"].displayindex = this.datagridview1.columns.count - 1;
this.datagridview1.columns["xg"].displayindex = this.datagridview1.columns.count - 2;

其中有一个utils类是用于查询,新增修改删的。创建一个utils类,

复制项目的代码

C#winform窗口登录和数据的增删改查

using system;
using system.collections.generic;
using system.data;
using system.data.sqlclient;
using system.linq;
using system.text;
using system.windows.forms;

 

 

{
/// <summary>
/// 增删改查
/// </summary>
class utils
{
public static void updatedata(string sql)
{
sqlconnection con = new sqlconnection();
con.connectionstring = system.configuration.configurationmanager.connectionstrings["datebase"].connectionstring.tostring();
con.open();
sqlcommand com = new sqlcommand();
com.connection = con;
com.commandtype = commandtype.text;
com.commandtext = sql;
sqldatareader dr = com.executereader();//执行sql语句
dr.close();
con.close();
}
public static datatable getdataset(string safesql)
{
sqlconnection con = new sqlconnection();
con.connectionstring = system.configuration.configurationmanager.connectionstrings["datebase"].connectionstring.tostring();
try
{
dataset ds = new dataset();
sqlcommand cmd = new sqlcommand(safesql, con);
cmd.commandtimeout = 3000;
sqldataadapter da = new sqldataadapter(cmd);
da.fill(ds);
return ds.tables[0];
}
catch (exception ex)
{
if (ex.message.contains("连接超时时间已到"))
{
messagebox.show("连接服务器超时!", "提示");
return null;
}
else
{
throw ex;
}

}
finally
{
if (con != null && con.state == system.data.connectionstate.open)
{
con.close();
}
else if (con != null && con.state == system.data.connectionstate.broken)
{
con.close();
}
}
}
}
}

添加两个引用

C#winform窗口登录和数据的增删改查

六、添加一个配置文件

C#winform窗口登录和数据的增删改查

打开配置文件加入下面的代码,也就是数据库的连接,改成你自己的。

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configsections>
</configsections>
<connectionstrings>
<add name="datebase" connectionstring="server=.;database=northwind;uid=sa;pwd=sa" />
</connectionstrings>
</configuration>

 到这里就可以查询了,可以先在数据加一条数据用来测试。

C#winform窗口登录和数据的增删改查

七、新增,我们在建立一个form3  这样做的好处是保存的时候好操作。如图

C#winform窗口登录和数据的增删改查

加一个改造方法,修改的时候就可以把选到的那一列带过来。

public form3()
{
//用于判断新增和修改。
arg = false;
initializecomponent();
}

private string id;
private string name; private string country;
bool arg = false;
/// <summary>
/// 修改构造方法
/// </summary>
/// <param name="id"></param>
/// <param name="name"></param>
/// <param name="country"></param>
public form3(string id, string name, string country)
{
this.id = id;
this.name = name;
this.country = country;
arg = true;
initializecomponent();
}

 

 给窗口绑定一个显示事件

 

C#winform窗口登录和数据的增删改查

事件方法

private void form3_shown(object sender, eventargs e)
{
if (arg)
{
if (id != null)
{
this.textbox1.text = id;
this.textbox2.text = name;
this.textbox3.text = country;
}
}
}

点击保存按钮

 

private void button1_click(object sender, eventargs e)
{
if (arg)
{
//update
if ("".equals(this.textbox1.text.trim()))
{
messagebox.show("id值不能为空");
return;
}
string sql1 = "delete from customer where customerid='" + id + "'; insert into customer(customerid,companyname,country) values('" + this.textbox1.text + "','" + this.textbox2.text + "','" + this.textbox3.text + "');";
utils.updatedata(sql1);
messagebox.show("修改成功!");
this.close();
}
else
{
//insert
string sql2 = " insert into customer(customerid,companyname,country) values('" + this.textbox1.text + "','" + this.textbox2.text + "','" + this.textbox3.text + "');";
utils.updatedata(sql2);
messagebox.show("添加成功!");
this.close();
}
}

八、回到form2 双击新增按钮,打开新增页面,就可以测试新增了。

代码

form3 f = new form3();
f.showdialog();

C#winform窗口登录和数据的增删改查

九、下来我们做修改和删除。在form2里面给datagridview加个点击事件,用来删除和修改

C#winform窗口登录和数据的增删改查

 

 点击事件代码

private void datagridview1_cellcontentclick(object sender, datagridviewcelleventargs e)
{
if (e.rowindex >= 0)
{
datagridviewcolumn colunm = this.datagridview1.columns[e.columnindex];
if (colunm is datagridviewbuttoncolumn)
{
string text = colunm.headertext;
if ("删除操作".equals(text.trim()))
{
string str = this.datagridview1.rows[e.rowindex].cells["id"].value.tostring().trim();
string sql = "delete from customer where customerid='" + str + "'";
try
{
utils.updatedata(sql);
messagebox.show("删除成功!", "提示");
button1_click(sender, e);
}
catch (exception)
{

}
}
if (colunm is datagridviewbuttoncolumn)
{
string id = this.datagridview1.rows[e.rowindex].cells["id"].value.tostring().trim();
string name = this.datagridview1.rows[e.rowindex].cells["公司名称"].value.tostring().trim();
string country = this.datagridview1.rows[e.rowindex].cells["国家"].value.tostring().trim();
string text1 = colunm.headertext;
if ("修改操作".equals(text1.trim()))
{
form3 f = new form3(id, name, country);
f.showdialog();

button1_click(sender, e);
}
}
}
}
}
}
}

 

可以测试了

C#winform窗口登录和数据的增删改查

C#winform窗口登录和数据的增删改查

完事了。写的不好,有疑问可以加微信或者qq都是 78474580