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

工具:VS2013

数据库SqlServer2008

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

资料部分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

 

一、新建项目

  

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

三、双击登录按钮,在双击方法里面写入下面代码。(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();
}

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

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

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

删除按钮

 

 修改按钮

五、双击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 form 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 邮编 form 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类,

复制下面的代码

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();
}
}
}
}
}

添加两个引用

六、添加一个配置文件

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

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
</configSections>
<connectionStrings>
<add name="database" connectionString="server=.;database=Northwind;uid=sa;pwd=sa" />
</connectionStrings>
</configuration>

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

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

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

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();
}

 

 给窗口绑定一个显示事件

 

事件方法

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 form 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();

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

 

 点击事件代码

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 form 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);
}
}
}
}
}
}
}

 

可以测试了

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

 

posted @ 2019-01-10 12:59  今天你努力了吗?  阅读(10166)  评论(8编辑  收藏  举报