通过几天的努力后,对datagridview使用作一些简要的介绍,该实例主要运用与通过对datagridview操作。对数据进行增删改查操作时,进行逻辑判断执行相关操作。简单的使用委托功能,实现子画面数据更新操作后,主画面也执行相关的刷新操作,达到数据实时跟新。另外对界面的布局花了点功夫,给予视觉感受稍微好点。话不多少,随小编进入实际练习的环节。
开发环境
开发工具:Microsoft Visual Studio 旗舰版、SQL Server 2008.
开发环境:.NET Framework 4 Client Profile.
实现步骤
1、采用MVC思想建立框架、建立PERSON_T表格;
首先,了解什么是MVC框架,MVC全名是Model View Controller,是模型(model)-视图(view)-控制器(controller)的缩写,一种软件设计典范,用于组织代码用一种业务逻辑和数据显示分离的方法,这个方法的假设前提是如果业务逻辑被聚集到一个部件里面,而且界面和用户围绕数据的交互能被改进和个性化定制而不需要重新编写业务逻辑MVC被独特的发展起来用于映射传统的输入、处理和输出功能在一个逻辑的图形化用户界面的结构中。
我在VS项目中建立一个目录如下图
然后,在SQL2008中FMSDB数据库中建立PERSON_T表;具体代码见下方:
1: USE [FMSDB]
2: GO
3:
4: /****** Object: Table [dbo].[PERSON_T] Script Date: 08/05/2013 22:40:39 ******/
5: SET ANSI_NULLS ON
6: GO
7:
8: SET QUOTED_IDENTIFIER ON
9: GO
10:
11: CREATE TABLE [dbo].[PERSON_T](
12: [ID] [nvarchar](50) NULL,
13: [NAME] [nvarchar](50) NULL,
14: [AGE] [int] NULL,
15: [POSITION] [nvarchar](50) NULL,
16: [HOMEADDRESS] [nvarchar](50) NULL,
17: [IDENTIFYNUMBER] [nvarchar](50) NULL
18: ) ON [PRIMARY]
19:
20: GO
.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }
2、视图层设置属性
MaximizeBox 设置为false 去除最大化窗口
MinimizeBox 设置为false 去除最小化窗口
StarPosition 设置为CenterScreen 画面启动居中
主画面lable居中采用 TextAlign设置为 MiddleCenter
主画面datagridview靠下 将Dock设置为 Bottom
其余见最下面源码下载
具体运行效果图见下方
视图层MainFrom具体代码见下方
1: using System;
2: using System.Collections.Generic;
3: using System.Data;
4: using System.Windows.Forms;
5: using ListBoxUnit1.Core;
6:
7:
8: namespace ListBoxUnit1
9: {
10: public partial class MainForm : Form
11: {
12: private Controller Control;
13:
14: public MainForm()
15: {
16: InitializeComponent();
17: Control = new Controller();
18: }
19:
20: private void MainForm_Load(object sender, EventArgs e)
21: {
22: dataGridView1.Show();
23: List<Person> persons = new List<Person>();
24:
25: persons = Control.GetUserInfo();
26: for (int i = 0; i < persons.Count; i++)
27: {
28: Person p = (Person) persons[i];
29: dataGridView1.Rows.Add();
30: dataGridView1.Rows[i].Cells["Column1"].Value = p.ID;
31: dataGridView1.Rows[i].Cells["Column2"].Value = p.Name;
32: dataGridView1.Rows[i].Cells["Column3"].Value = p.Age;
33: dataGridView1.Rows[i].Cells["Column4"].Value = p.Position;
34: dataGridView1.Rows[i].Cells["Column5"].Value = p.HomeAddresss;
35: dataGridView1.Rows[i].Cells["Column6"].Value = p.IdentifyNumber;
36: }
37: }
38:
39: private void ToolStripMenuItem_Click(object sender, EventArgs e)
40: {
41: string name;
42: if (dataGridView1.SelectedRows.Count>0)
43: {
44: DialogResult comfirm = MessageBox.Show("确定删除信息...", "确定删除", MessageBoxButtons.YesNo,
45: MessageBoxIcon.Exclamation);
46: if (comfirm == DialogResult.Yes)
47: {
48: name = dataGridView1.CurrentRow.Cells["Column2"].Value.ToString();
49: bool result = Control.DeleteUser(name);
50: if (result == true)
51: {
52: MessageBox.Show("成功删除用户选中信息");
53: QueryDataGridView();
54: }
55: else
56: {
57: MessageBox.Show("删除用户失败!");
58:
59: }
60: }
61: }
62: }
63:
64: private void btnQuery_Click(object sender, EventArgs e)
65: {
66: string name = txtUserName.Text;
67: string identifyNumber = txtIdentifyNumber.Text;
68: QueryDataGridView();
69: if (name==""&&identifyNumber=="")
70: {
71: lbMessage.Text = "请选择查询用户的条件!";
72: return;
73: }
74: else
75: {
76: if (name!="")
77: {
78: DataSet ds = Control.QueryByName(name);
79: dataGridView1.Rows.Clear();
80: for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
81: {
82: dataGridView1.Rows.Add();
83: dataGridView1.Rows[i].Cells["Column1"].Value = ds.Tables[0].Rows[i]["ID"].ToString();
84: dataGridView1.Rows[i].Cells["Column2"].Value = ds.Tables[0].Rows[i]["NAME"].ToString();
85: dataGridView1.Rows[i].Cells["Column3"].Value = Convert.ToInt32(ds.Tables[0].Rows[i]["AGE"]);
86: dataGridView1.Rows[i].Cells["Column4"].Value = ds.Tables[0].Rows[i]["POSITION"].ToString();
87: dataGridView1.Rows[i].Cells["Column5"].Value = ds.Tables[0].Rows[i]["HOMEADDRESS"].ToString();
88: dataGridView1.Rows[i].Cells["Column6"].Value = ds.Tables[0].Rows[i]["IDENTIFYNUMBER"].ToString();
89: }
90: lbMessage.Text ="已查询出"+txtUserName.Text+"用户信息";
91: return;
92: }
93: else
94: {
95: if (identifyNumber != "")
96: {
97: DataSet ds=Control.QueryIdentifyNumber(identifyNumber);
98: dataGridView1.Rows.Clear();
99: for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
100: {
101: dataGridView1.Rows.Add();
102: dataGridView1.Rows[i].Cells["Column1"].Value = ds.Tables[0].Rows[i]["ID"].ToString();
103: dataGridView1.Rows[i].Cells["Column2"].Value = ds.Tables[0].Rows[i]["NAME"].ToString();
104: dataGridView1.Rows[i].Cells["Column3"].Value = Convert.ToInt32(ds.Tables[0].Rows[i]["AGE"]);
105: dataGridView1.Rows[i].Cells["Column4"].Value = ds.Tables[0].Rows[i]["POSITION"].ToString();
106: dataGridView1.Rows[i].Cells["Column5"].Value = ds.Tables[0].Rows[i]["HOMEADDRESS"].ToString();
107: dataGridView1.Rows[i].Cells["Column6"].Value = ds.Tables[0].Rows[i]["IDENTIFYNUMBER"].ToString();
108: }
109: }
110: return;
111: }
112: }
113: }
114:
115:
116: private void btnEdit_Click(object sender, EventArgs e)
117: {
118: //DataSet ds=dataGridView1.SelectedCells.v
119: //DataSet ds=new DataSet();
120: int index = dataGridView1.SelectedRows[0].Index;
121: Person p=new Person();
122: p.ID = dataGridView1.Rows[index].Cells["Column1"].Value.ToString();
123: p.Name = dataGridView1.Rows[index].Cells["Column2"].Value.ToString();
124: p.Age = int.Parse(dataGridView1.Rows[index].Cells["Column3"].Value.ToString());
125: p.Position = dataGridView1.Rows[index].Cells["Column4"].Value.ToString();
126: p.HomeAddresss = dataGridView1.Rows[index].Cells["Column5"].Value.ToString();
127: p.IdentifyNumber = dataGridView1.Rows[index].Cells["Column6"].Value.ToString();
128: EditUserForm editUserForm = new EditUserForm(p);
129: editUserForm.Query+=new EditUserForm.QueryEventHandler(QueryDataGridView);
130: editUserForm.ShowDialog();
131: }
132:
133: private void btnAddUserInfo(object sender, EventArgs e)
134: {
135: AddUserForm addUserForm=new AddUserForm();
136: addUserForm.query+=new AddUserForm.QueryEventHandler(QueryDataGridView);
137: addUserForm.ShowDialog();
138: }
139:
140: public void QueryDataGridView()
141: {
142: List<Person> dgv = Control.GetUserInfo();
143: dataGridView1.Rows.Clear();
144: for (int i = 0; i < dgv.Count; i++)
145: {
146: Person p = (Person)dgv[i];
147: dataGridView1.Rows.Add();
148: dataGridView1.Rows[i].Cells["Column1"].Value = p.ID;
149: dataGridView1.Rows[i].Cells["Column2"].Value = p.Name;
150: dataGridView1.Rows[i].Cells["Column3"].Value = p.Age;
151: dataGridView1.Rows[i].Cells["Column4"].Value = p.Position;
152: dataGridView1.Rows[i].Cells["Column5"].Value = p.HomeAddresss;
153: dataGridView1.Rows[i].Cells["Column6"].Value = p.IdentifyNumber;
154: }
155: }
156: }
157: }
158:
.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }
3、控制层主要编写逻辑控制,具体Controller.cs代码见下方:
1: using System.Collections.Generic;
2: using System.Data;
3: using ListBoxUnit1.DataGateway;
4:
5: namespace ListBoxUnit1.Core
6: {
7: public class Controller
8: {
9: public SelectGW GW;
10: public UpdateGW UGW;
11: public Controller()
12: {
13: GW =new SelectGW();
14: UGW=new UpdateGW();
15: }
16:
17: public List<Person> GetUserInfo()
18: {
19: List<Person> persons = new List<Person>();
20: DataSet ds = GW.GetPersonData();
21: if (ds.Tables[0].Rows.Count > 0)
22: for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
23: {
24: Person p = new Person();
25: p.ID = ds.Tables[0].Rows[i][0].ToString();
26: p.Name = ds.Tables[0].Rows[i][1].ToString();
27: p.Age = int.Parse(ds.Tables[0].Rows[i][2].ToString());
28: p.Position = ds.Tables[0].Rows[i][3].ToString();
29: p.HomeAddresss = ds.Tables[0].Rows[i][4].ToString();
30: p.IdentifyNumber = ds.Tables[0].Rows[i][5].ToString();
31: persons.Add(p);
32: }
33: return persons;
34: }
35:
36: public bool DeleteUser(string name)
37: {
38: bool result=false;
39: int i= GW.DeleteUserInfoData(name);
40: if (i > 0)
41: {
42: result = true;
43: }
44: return result;
45: }
46:
47:
48: public DataSet QueryByName(string name)
49: {
50: DataSet ds = GW.GetUserByName(name);
51: return ds;
52: }
53:
54: public DataSet QueryIdentifyNumber(string identifyNumber)
55: {
56: DataSet ds = GW.GetUserByIdentifyNumber(identifyNumber);
57: return ds;
58: }
59:
60: public bool UpdateUserByName(string id,string name,string age,string postion,string address,string identifyNumber)
61: {
62: if (id==null)
63: {
64: return false;
65: }
66: else if (name==null)
67: {
68: return false;
69: }
70: else if (age==null)
71: {
72: return false;
73: }
74: else if (postion==null)
75: {
76: return false;
77: }
78: else if(address==null)
79: {
80: return false;
81: }
82: else if(identifyNumber==null)
83: {
84: return false;
85: }
86: else
87: {
88: bool result = UGW.UpdateUserByName(id, name, age, postion, address, identifyNumber);
89: return result;
90: }
91: }
92:
93: public bool InsertUserInfo(string id, string name, string age, string postion, string address,string identifyNumber)
94: {
95: bool result = UGW.InsertUserInfo(id, name, age, postion, address, identifyNumber);
96: return result;
97: }
98: }
99: }
.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }4、底层数据库层查询操作具体SelectGW.cs代码见下:
1: using System;
2: using System.Data;
3: using System.Data.SqlClient;
4: using System.Configuration;
5:
6: namespace ListBoxUnit1.DataGateway
7: {
8: public class SelectGW
9: {
10: private string connectString = "";
11:
12: public SelectGW()
13: {
14: connectString = ConfigurationManager.AppSettings["myDatabase.Conn"];
15: }
16:
17: public SqlConnection GetSqlConnection()
18: {
19: SqlConnection conn = new SqlConnection(connectString);
20: conn.Open();
21: return conn;
22: }
23:
24: public DataSet GetPersonData()
25: {
26: DataSet ds = new DataSet();
27: string sqlText = @"SELECT * FROM PERSON_T;";
28: try
29: {
30: SqlConnection conn = GetSqlConnection();
31: SqlCommand sqlCommand = conn.CreateCommand();
32: sqlCommand.CommandText = sqlText;
33: sqlCommand.CommandType = CommandType.Text;
34: SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(sqlCommand);
35:
36: sqlDataAdapter.Fill(ds);
37: }
38: catch (Exception ex)
39: {
40:
41: }
42: return ds;
43: }
44:
45: public int DeleteUserInfoData(string NAME)
46: {
47: string sqlText = @"delete FROM PERSON_T where NAME='{0}';";
48: sqlText = string.Format(sqlText, NAME);
49: try
50: {
51: SqlConnection conn = GetSqlConnection();
52: SqlCommand sqlCommand = conn.CreateCommand();
53: sqlCommand.CommandText = sqlText;
54: sqlCommand.CommandType = CommandType.Text;
55: int i=sqlCommand.ExecuteNonQuery();
56: return i;
57: }
58: catch (Exception ex)
59: {
60: return 0;
61: }
62: }
63:
64:
65: public DataSet GetUserByName(string name)
66: {
67: DataSet ds = new DataSet();
68: string sqlText = @"SELECT * FROM PERSON_T where NAME='{0}';";
69: sqlText = string.Format(sqlText, name);
70: try
71: {
72: SqlConnection conn = GetSqlConnection();
73: SqlCommand sqlCommand = conn.CreateCommand();
74: sqlCommand.CommandText = sqlText;
75: sqlCommand.CommandType = CommandType.Text;
76: SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(sqlCommand);
77:
78: sqlDataAdapter.Fill(ds);
79: }
80: catch (Exception ex)
81: {
82:
83: }
84: return ds;
85: }
86:
87: public DataSet GetUserByIdentifyNumber(string identifyNumber)
88: {
89: DataSet ds = new DataSet();
90: string sqlText = @"SELECT * FROM PERSON_T where IDENTIFYNUMBER='{0}';";
91: sqlText = string.Format(sqlText, identifyNumber);
92: try
93: {
94: SqlConnection conn = GetSqlConnection();
95: SqlCommand sqlCommand = conn.CreateCommand();
96: sqlCommand.CommandText = sqlText;
97: sqlCommand.CommandType = CommandType.Text;
98: SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(sqlCommand);
99:
100: sqlDataAdapter.Fill(ds);
101: }
102: catch (Exception ex)
103: {
104:
105: }
106: return ds;
107: }
108: }
109: }
.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }
5、底层数据库层插入与更新操作具体UpdateGW.cs代码见下:
1: using System;
2: using System.Configuration;
3: using System.Data;
4: using System.Data.SqlClient;
5:
6:
7: namespace ListBoxUnit1.DataGateway
8: {
9: public class UpdateGW
10: {
11: private string connectString = "";
12:
13: public UpdateGW()
14: {
15: connectString = ConfigurationManager.AppSettings["myDatabase.Conn"];
16: }
17:
18: public SqlConnection GetSqlConnection()
19: {
20: SqlConnection conn = new SqlConnection(connectString);
21: conn.Open();
22: return conn;
23: }
24:
25:
26: public bool UpdateUserByName(string Id, string Name, string Age, string Postion, string Address,
27: string IdentifyNumber)
28: {
29: string sqlText =
30: @"update PERSON_T set ID='{0}',NAME='{1}',AGE='{2}',POSITION='{3}',HOMEADDRESS='{4}',IDENTIFYNUMBER='{5}' FROM PERSON_T where NAME='{1}';";
31: sqlText = string.Format(sqlText, Id, Name, Age, Postion, Address, IdentifyNumber);
32: try
33: {
34: SqlConnection conn = GetSqlConnection();
35: SqlCommand sqlCommand = conn.CreateCommand();
36: sqlCommand.CommandText = sqlText;
37: sqlCommand.CommandType = CommandType.Text;
38: int i = sqlCommand.ExecuteNonQuery();
39: return true;
40:
41: }
42: catch (Exception ex)
43: {
44: return false;
45: }
46: }
47:
48: public bool InsertUserInfo(string Id, string Name, string Age, string Postion, string Address, string IdentifyNumber)
49: {
50: string sqlText =
51: @"Insert into PERSON_T (ID,NAME,AGE,POSITION,HOMEADDRESS,IDENTIFYNUMBER)Values('{0}','{1}','{2}','{3}','{4}','{5}');";
52: sqlText = string.Format(sqlText, Id, Name, Age, Postion, Address, IdentifyNumber);
53: try
54: {
55: SqlConnection conn = GetSqlConnection();
56: SqlCommand sqlCommand = conn.CreateCommand();
57: sqlCommand.CommandText = sqlText;
58: sqlCommand.CommandType = CommandType.Text;
59: int i = sqlCommand.ExecuteNonQuery();
60: return true;
61: }
62: catch (Exception ex)
63: {
64: return false;
65: }
66: }
67: }
68: }
运行效果图
主画面效果图,主要分查询、增加、修改、删除功能,另外下方显示用户信息。
查询分为姓名或身份证号查询用户信息
点击edit按钮后跳出界面如下所示,带出选中datagridview那行信息,进行更新操作。
按确认完成更新操作
点击Add按钮后跳出界面如下所示,插入数据界面
若添加数据与已有数据重复会有提示,具体见下图
在datagridview中右键后跳出确定/取消,删除选中用户信息后界面,删除用户后主画面更新
技术点
1、子画面进行用户的增加或修改成功后,主画面datagridview也会有相应变动,采用委托功能。
2、contextMenuStrip1与datagridview绑定,右击实现删除功能;
3、界面布局相应属性设置,使界面美观。
4、牢记面向对象的编程思想,创建对象,实例化对象。
疑难点
1、熟练使用listbox、dateset、dategridview中数据之间的传递和赋值
2、委托方法使用加强锻炼,灵活运用到实际项目中,提高程序稳定性
感受
本人通过这个小实例练习过后,已经对于面向对象编程有了一定的熟悉,由于基础知识欠佳,对于某些赋值处理过程不是很熟练,从而花费大量时间查阅资料。想要快速完成代码,还得从基础下手,理解编程思想,多练多看多问,才能迅速提升编程能力。总之,合理利用时间,有效利用资源。我相信,you are best!
.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }