C#-窗体通讯录系统

 

1.首先创建DBhelp类用来连接数据库,代码如下:

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

namespace TongxunLu
{
  public static   class DBHelp
    {
       static  string sqlcon = "Data Source=.;Initial Catalog=TXL;Integrated Security=True";
        public static  SqlConnection con = new System.Data.SqlClient.SqlConnection(sqlcon);
       public static  SqlCommand cmd = new SqlCommand();
      
    }
}

登录页面:

 双加登录里面代码:

 private void btnOK_Click(object sender, EventArgs e)
        {
            //验证用户名与密码非空
            if (txtUserName.Text == "")
            {
                MessageBox.Show("用户名不能为空,请输入!");
                txtUserName.Focus();
                return;
            }
            if (txtUserPwd.Text == "")
            {
                MessageBox.Show("密码不能为空,请输入!");
                txtUserPwd.Focus();
                return;
            }
            //定义链接字符串和链接对象        
            string sqlcon = "Data Source=.;Initial Catalog=TXL;Integrated Security=True";
            SqlConnection con = new System.Data.SqlClient.SqlConnection(sqlcon);
            //操作数据库,实现登录功能
            try
            {
                con.Open();
                string sqlcomm = "select  distinct COUNT(*) from Users where UserName='" + txtUserName.Text + "'  and Password='" + txtUserPwd.Text + "'";

                SqlCommand cmd = new System.Data.SqlClient.SqlCommand(sqlcomm, con);
                //cmd.Connection = con;
                //cmd.CommandText = sqlcomm;

                if ((int)cmd.ExecuteScalar() == 1)
                {
                   // MessageBox.Show("登录成功");
                    Users.UserName = txtUserName.Text;
                    FrmMain fmain = new FrmMain();
                    fmain.Show();
                }
                else
                {
                    MessageBox.Show("登录失败");
                }

                // MessageBox.Show("数据库打开成功", "提示信息", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "提示信息", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning);
            }
            finally
            {
                con.Close();
                // MessageBox.Show("数据库成功关闭", "提示信息", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning);
            }              
        }

双击取消,里面代码:

private void btnCacel_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

 输入用户表里面的信息,进行登录:

2.创建主页面:

 添加菜单栏、工具栏、状态栏

菜单栏控件:MenuStrip  以mus开头命名

项目名称以tsm开头 项目里的项目以tsmi开头命名

工具栏控件:ToolStrip  项显示图片和文本更改属性DisplayStyle,工具栏:以tst开头

状态栏控件:StatusStrip,状态栏:以tss命名开头

 

当页面加载那个用户登录,状态用Label控件就显示谁的名字,代码:

 private void FrmMain_Load(object sender, EventArgs e)
        {
            //接受登录名
            toolStripStatusLabel2.Text += Users.UserName;
            toolStripStatusLabel3.Text += GetNum(Users.UserName).ToString();
           LoadGroup();
        }

主页面里面的详细功能代码,如下:

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;
using System.Data.SqlClient;

namespace TongxunLu
{
    public partial class FrmMain : Form
    {
        public FrmMain()
        {
            InitializeComponent();
        }
        //显示添加窗体
        public void add()
        {
            frmAdd fadd = new frmAdd();

            fadd.Show();
        }
        //显示修改窗体
        public void edit()
        {
            frmEdit fedit = new frmEdit();
            fedit.Show();
        }
        //显示查询窗体
        public void seacher()
        {
            frmSeach fseacher=new frmSeach ();
            fseacher.Show();
        }
        //统计登录联系人的个数
        public int GetNum(string str1)
        {
            int num = 0;
            try
            {
                DBHelp.con.Open();
                string sqlcomm = string.Format("select count(*) from BUsicInfo where UserName='{0}'",str1);
                DBHelp.cmd.Connection = DBHelp.con;
                DBHelp.cmd.CommandText = sqlcomm;
                num = (int)DBHelp.cmd.ExecuteScalar();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                DBHelp.con.Close();
            }
            return num;
 
        }
        //统计登录联系人分组的个数
        public int GetGroupsNum()
        {
            int num = 0;
            try
            {
                DBHelp.con.Open();
                string sqlcomm = string.Format("select count(*) from BUsicInfo where UserName='{0}' and  groups='{1}'",Users.UserName,treeView1.SelectedNode.Text );
                DBHelp.cmd.Connection = DBHelp.con;
                DBHelp.cmd.CommandText = sqlcomm;
                num = (int)DBHelp.cmd.ExecuteScalar();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                DBHelp.con.Close();
            }
            return num;

        }

        //加载treeview控件

        public void LoadGroup()
        {
            try
            {
                DBHelp.con.Open();
                string sqlcomm = string.Format("select groups from busicInfo where userName='{0}'",Users.UserName);
                DBHelp.cmd.Connection = DBHelp.con;
                DBHelp.cmd.CommandText = sqlcomm;
                SqlDataReader dr = DBHelp.cmd.ExecuteReader();
                while(dr.Read())
                {
                    treeView1.Nodes.Add(dr[0].ToString());
                }
                dr.Close();

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                DBHelp.con.Close();
            }
        }

        //加载ListView控件
        public void loadList()
        {
             if (treeView1.Nodes.Count == 0)
            {
                MessageBox.Show("请重新加载");
                listView1.Items.Clear();
                return;
            }
            if (treeView1.SelectedNode.Index >= 0)
            {
                listView1.Clear();
                listView1.Columns.Add("姓名", 100);
                listView1.Columns.Add("工作单位", 100);
                listView1.Columns.Add("联系电话", 100);
                listView1.Columns.Add("电子邮箱", 100);
                listView1.Columns.Add("QQ", 100);

                try
                {
                    DBHelp.con.Open();
                    string sqlcomm = string.Format("select * from busicInfo where userName='{0}' and Groups='{1}'",Users.UserName,treeView1.SelectedNode.Text);
                    DBHelp.cmd.CommandText = sqlcomm;
                    DBHelp.cmd.Connection = DBHelp.con;
                    SqlDataReader dr = DBHelp.cmd.ExecuteReader();
                    while(dr.Read())
                    {
                        ListViewItem lvi = new ListViewItem();
                        lvi.Tag = dr[0];
                        lvi.Text = dr[3].ToString();
                        lvi.SubItems.Add(dr[4].ToString());
                        lvi.SubItems.Add(dr[5].ToString());
                        lvi.SubItems.Add(dr[6].ToString());
                        lvi.SubItems.Add(dr[7].ToString());
                        listView1.Items.Add(lvi); 
                    }
                    dr.Close();

                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
                finally
                {
                    DBHelp.con.Close();
                }
            }
            
        }
        
        private void 增加联系人ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            add();
        }

        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            add();
        }

        private void toolStripButton4_Click(object sender, EventArgs e)
        {
            seacher();
        }

        private void FrmMain_Load(object sender, EventArgs e)
        {
            //接受登录名
            toolStripStatusLabel2.Text += Users.UserName;
            toolStripStatusLabel3.Text += GetNum(Users.UserName).ToString();
           LoadGroup();
        }

        private void menuStrip1_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {

        }

        private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)
        {
           loadList();
           toolStripStatusLabel3.Text = GetGroupsNum().ToString();
            
        }


       
        
    }
}

3.添加联系人页面:

Tablcontrol控件:分页选项:用来分页:基本信息和其他信息 

双击确定,里面代码:

 private void btnAdd_Click(object sender, EventArgs e)
        {
            try
            {
                DBHelp.con.Open();

          DBHelp.cmd.CommandText =string.Format("insert into BusicInfo(userName,Groups,Name,workUnit,Phone,Email,QQ)values('{0}','{1}','{2}','{3}','{4}','{5}','{6}')",Users.UserName,cmbGroup.SelectedValue,txtName.Text,txtWorkUnit.Text,txtPhone.Text,txtEmail.Text,txtQQ.Text);
          DBHelp.cmd.Connection = DBHelp.con;
          if ((int)DBHelp.cmd.ExecuteNonQuery() == 1)
          {
              MessageBox.Show("添加成功");

          }
          else
          {
              MessageBox.Show("失败");
          }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                DBHelp.con.Close();
            }

        }

 加载页面,双击压面,里面代码

 public void LoadGroup()
        {
            try
            {
                DBHelp.con.Open();
                string sqlcomm = string.Format("select groups from busicInfo where userName='{0}'", Users.UserName);
                DBHelp.cmd.Connection = DBHelp.con;
                DBHelp.cmd.CommandText = sqlcomm;
                SqlDataReader dr = DBHelp.cmd.ExecuteReader();
                while (dr.Read())
                {
                    cmbGroup.Items.Add(dr[0].ToString());
                }
                dr.Close();

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                DBHelp.con.Close();
            }
        }

        private void frmAdd_Load(object sender, EventArgs e)
        {
            LoadGroup();
        }

 

 4.修改页面:

5.查询页面:

 

 双击查询按钮,里面代码:

private void btnSeach_Click(object sender, EventArgs e)
        {

            string sqlcomm = "";
            if(txtUserName.Text==""&&txtUserPhone.Text=="")
            {
                sqlcomm = string.Format("select * from  BusicInfo ");
            
            }
            else if (txtUserName.Text == "")
            {
                sqlcomm = string.Format("select * from  BusicInfo  where Phone='%{0}%' ", txtUserPhone.Text);

            }
            else if (txtUserPhone.Text == "")
            {
                sqlcomm = string.Format("select * from  BusicInfo  where UserName='{0}%' ", txtUserName.Text);
            }
            else
            {
                sqlcomm = string.Format("select * from  BusicInfo  where UserName='{0}%' and Phone='{1}%' ", txtUserName.Text, txtUserPhone.Text);
            }
           
            try
            {
                DBHelp.con.Open();

                SqlDataAdapter da = new SqlDataAdapter(sqlcomm,DBHelp.con);
                DataSet ds = new DataSet();
               
                da.Fill(ds);
                dataGridView1.DataSource = ds.Tables[0];

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                DBHelp.con.Close();
            }


        }

功能未完全实现,只是例子。

  • 9
    点赞
  • 66
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 4
    评论
好的,以下是一个简单的C#窗体个人通讯录系统代码示例: 1. 创建数据库表 在SQL Server中创建一个名为Contact的数据库,包含一个名为Contacts的表,表结构如下: ``` CREATE TABLE Contacts ( ID INT PRIMARY KEY IDENTITY, Name VARCHAR(50), Phone VARCHAR(20), Email VARCHAR(50) ) ``` 2. 创建C#窗体项目 在Visual Studio中创建一个Windows Forms应用程序,然后添加一个DataGridView控件和若干个文本框和按钮控件,用于实现添加、编辑、删除、搜索联系人的功能。 3. 连接数据库 在代码中添加以下代码,连接到数据库: ``` string connectionString = "Data Source=(local);Initial Catalog=Contact;Integrated Security=True"; SqlConnection connection = new SqlConnection(connectionString); ``` 4. 显示联系人 在窗体加载时,从数据库中读取联系人信息,显示在DataGridView控件中: ``` private void Form1_Load(object sender, EventArgs e) { string query = "SELECT * FROM Contacts"; SqlDataAdapter dataAdapter = new SqlDataAdapter(query, connection); DataTable dataTable = new DataTable(); dataAdapter.Fill(dataTable); dataGridView1.DataSource = dataTable; } ``` 5. 添加联系人 在添加按钮的Click事件中,将输入的联系人信息插入到数据库中,并刷新DataGridView控件: ``` private void btnAdd_Click(object sender, EventArgs e) { string name = txtName.Text; string phone = txtPhone.Text; string email = txtEmail.Text; string query = $"INSERT INTO Contacts (Name, Phone, Email) VALUES ('{name}', '{phone}', '{email}')"; SqlCommand command = new SqlCommand(query, connection); connection.Open(); command.ExecuteNonQuery(); connection.Close(); Form1_Load(sender, e); } ``` 6. 编辑联系人 在DataGridView控件中双击某一行时,将该行对应的联系人信息显示在文本框中,用户可以编辑后保存到数据库中: ``` private void dataGridView1_CellDoubleClick(object sender, DataGridViewCellEventArgs e) { DataGridViewRow row = dataGridView1.Rows[e.RowIndex]; txtName.Text = row.Cells[1].Value.ToString(); txtPhone.Text = row.Cells[2].Value.ToString(); txtEmail.Text = row.Cells[3].Value.ToString(); } ``` 在保存按钮的Click事件中,将修改后的联系人信息更新到数据库中,并刷新DataGridView控件: ``` private void btnSave_Click(object sender, EventArgs e) { string name = txtName.Text; string phone = txtPhone.Text; string email = txtEmail.Text; int id = int.Parse(dataGridView1.SelectedRows[0].Cells[0].Value.ToString()); string query = $"UPDATE Contacts SET Name='{name}', Phone='{phone}', Email='{email}' WHERE ID={id}"; SqlCommand command = new SqlCommand(query, connection); connection.Open(); command.ExecuteNonQuery(); connection.Close(); Form1_Load(sender, e); } ``` 7. 删除联系人 在删除按钮的Click事件中,从数据库中删除选中的联系人,并刷新DataGridView控件: ``` private void btnDelete_Click(object sender, EventArgs e) { int id = int.Parse(dataGridView1.SelectedRows[0].Cells[0].Value.ToString()); string query = $"DELETE FROM Contacts WHERE ID={id}"; SqlCommand command = new SqlCommand(query, connection); connection.Open(); command.ExecuteNonQuery(); connection.Close(); Form1_Load(sender, e); } ``` 8. 搜索联系人 在搜索按钮的Click事件中,根据输入的关键字从数据库中检索联系人信息,并显示在DataGridView控件中: ``` private void btnSearch_Click(object sender, EventArgs e) { string keyword = txtSearch.Text; string query = $"SELECT * FROM Contacts WHERE Name LIKE '%{keyword}%' OR Phone LIKE '%{keyword}%' OR Email LIKE '%{keyword}%'"; SqlDataAdapter dataAdapter = new SqlDataAdapter(query, connection); DataTable dataTable = new DataTable(); dataAdapter.Fill(dataTable); dataGridView1.DataSource = dataTable; } ``` 以上是一个简单的C#窗体个人通讯录系统代码示例,希望可以帮到您。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

喵俺第一专栏

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值