手把手教你用SQLServer连接Visual Studio2019并编写一个学生信息管理页面

目录

安装SQLServer

创建新项目

建数据库建表

窗体设计

代码实现

 整体效果


安装SQLServer

用SQLServer连接Visual Studio,首先需要下载SQLServer app。

下载教程,我之前写过,可以点击如下链接先下载安装SQLServer:

SQL Server(express)安装教程

创建新项目

安装好SQL之后,打开VisualStudio2019,新建一个window项目

,步骤如下:选择创建新项目

手把手教你用SQLServer连接Visual Studio2019并编写一个学生信息管理页面_第1张图片

选择Windows窗体应用(.NET Framework)  点击下一步。

手把手教你用SQLServer连接Visual Studio2019并编写一个学生信息管理页面_第2张图片

给文件命名为:WinFormsApplicationStudentManagement ,点击下一步

 手把手教你用SQLServer连接Visual Studio2019并编写一个学生信息管理页面_第3张图片

 点击创建,就建好了

手把手教你用SQLServer连接Visual Studio2019并编写一个学生信息管理页面_第4张图片

建数据库建表

项目建好之后我们先连接数据库。

1.找到服务器资源管理器

2.找到数据连接,右键,添加连接

手把手教你用SQLServer连接Visual Studio2019并编写一个学生信息管理页面_第5张图片

数据源选择Microsoft SQL Server数据库文件(SqlClient)

数据库文件名输入StudentManagement 这是我们创建的数据库的名称

登录方式身份验证,选Windows身份验证

点击确定

手把手教你用SQLServer连接Visual Studio2019并编写一个学生信息管理页面_第6张图片

点击这样就建好了数据库

手把手教你用SQLServer连接Visual Studio2019并编写一个学生信息管理页面_第7张图片

 下面我们新建两个表。

一个student表,存储学号(主键)、姓名、年龄、分数。

一个college表,存储专业号(主键),和专业名。

按照步骤:

选择刚建好的数据库,双击打开。

打开后找到表,右键,选择添加新表

手把手教你用SQLServer连接Visual Studio2019并编写一个学生信息管理页面_第8张图片

 添加新表后,会出现如下界面:

手把手教你用SQLServer连接Visual Studio2019并编写一个学生信息管理页面_第9张图片

按照我这样设计表,设计完成后,点击更新  注意要更改表名。

手把手教你用SQLServer连接Visual Studio2019并编写一个学生信息管理页面_第10张图片 点击更新后,会出现如下界面:点击更新数据库即可。

手把手教你用SQLServer连接Visual Studio2019并编写一个学生信息管理页面_第11张图片

点击更新数据库按钮。

手把手教你用SQLServer连接Visual Studio2019并编写一个学生信息管理页面_第12张图片

 这是刷新之后的样子,能看到刚才建立的student表。

手把手教你用SQLServer连接Visual Studio2019并编写一个学生信息管理页面_第13张图片

 同样方法,我们新建一个college表。

手把手教你用SQLServer连接Visual Studio2019并编写一个学生信息管理页面_第14张图片

 这是college表建好之后的样子。

手把手教你用SQLServer连接Visual Studio2019并编写一个学生信息管理页面_第15张图片

窗体设计

表建好了,我们开始设计窗体。

打开Form1.cs[Design]

设计如下页面

手把手教你用SQLServer连接Visual Studio2019并编写一个学生信息管理页面_第16张图片

 布局如下:

手把手教你用SQLServer连接Visual Studio2019并编写一个学生信息管理页面_第17张图片

组件在工具箱中添加;

组件name text 事件在属性中编辑

左部:name=groupbox1 text=学生列表

中间:name=groupbox2 text=学生详情

右边:name=groupbox3 text=操作

下边:richtextbox name=rtxtStudentList

写完是这样的。

手把手教你用SQLServer连接Visual Studio2019并编写一个学生信息管理页面_第18张图片

 再来设计里面的界面:

手把手教你用SQLServer连接Visual Studio2019并编写一个学生信息管理页面_第19张图片

设计好之后

label改text 分别改成 学号 姓名 年龄 分数

textbox改name 分别是txtId txtName txtAge txtScore

button改name和text

name分别改成 btnnew btnInsert btnUpdate btnDelete btnSave

text分别改成 新建 插入 更新 删除 保存

ComboBox改name改成cboColleges

手把手教你用SQLServer连接Visual Studio2019并编写一个学生信息管理页面_第20张图片

 忘了,学生列表里还要建一个listbox 名字是listStudent

手把手教你用SQLServer连接Visual Studio2019并编写一个学生信息管理页面_第21张图片

 布局部分完成了。

开始写代码了。

代码实现

我们使用的是Sqlconnection连接数据库,所以要新增引用

using System.Data.SqlClient;

手把手教你用SQLServer连接Visual Studio2019并编写一个学生信息管理页面_第22张图片

找到数据库,右键属性,找到连接字符串,全选复制到代码中。

手把手教你用SQLServer连接Visual Studio2019并编写一个学生信息管理页面_第23张图片

 我这是连好的:

手把手教你用SQLServer连接Visual Studio2019并编写一个学生信息管理页面_第24张图片

之后的代码如下:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace WindowsFormsApplicationNonetSql
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            LoadDatabase();
            BindStudentList();
            BindCollegeList();
        }
        string connectionString = @"Data Source=pc\sqlexpress;Initial Catalog=ailintext;Integrated Security=True";

        DataSet dataSet = new DataSet();

        DataTable students;
        DataTable colleges;
        private void BindStudentList()
        {

            listStudent.SelectedIndexChanged -= listStudent_SelectedIndexChanged;
            listStudent.DataSource = students;
            listStudent.DisplayMember = "student_name";
            listStudent.ValueMember = "student_id";
            listStudent.SelectedIndexChanged += listStudent_SelectedIndexChanged;

        }
        private void BindCollegeList()
        {

            listStudent.SelectedIndexChanged -= cboColleges_SelectedIndexChanged;
            cboColleges.DataSource = colleges;
            cboColleges.DisplayMember = "college_name";
            cboColleges.ValueMember = "college_id";
            listStudent.SelectedIndexChanged += cboColleges_SelectedIndexChanged;

        }

        private void LoadDatabase()
        {
            SqlConnection connection =new SqlConnection(connectionString);

            string selectCommand = "select * from student";

            SqlCommand command = new SqlCommand();
            command.CommandText = selectCommand;
            command.Connection = connection;
            //适配器
            SqlDataAdapter studentAdapter = new SqlDataAdapter();
            studentAdapter.SelectCommand = command;
            //读入数据 适配器填充数据
            studentAdapter.Fill(dataSet, "student");

            students = dataSet.Tables["student"];
            /*command.CommandText = "select * from college";*/

            /* SqlDataAdapter collegeAdapter = new SqlDataAdapter(command);
             collegeAdapter.Fill(dataSet, "college");

             colleges = dataSet.Tables["college"];*/
            students.PrimaryKey = new DataColumn[]
            {
               students.Columns["student_id"]
            };


            selectCommand = "select * from college";
            command.CommandText = selectCommand;

            SqlDataAdapter collegeAdapter = new SqlDataAdapter();
            collegeAdapter.SelectCommand = command;

            collegeAdapter.Fill(dataSet, "college");
            colleges = dataSet.Tables["college"];

            colleges.PrimaryKey = new DataColumn[]
            {
                colleges.Columns["college_id"]
            };
            DataRelation dr = new DataRelation(
                "FK_student_college",
                colleges.Columns["college_id"],
                students.Columns["college_id"]);

            dataSet.Relations.Add(dr);
        }

        private void listStudent_SelectedIndexChanged(object sender, EventArgs e)
        {
            //点击学生姓名,返回学生信息
            if (listStudent.SelectedIndex < 0)
            {
                return ;
            }
            //拿到信息
            DataRow student = students.Rows.Find(listStudent.SelectedValue);
            //显示信息
            txtId.Text = student["student_id"].ToString();
            txtName.Text = student["student_name"].ToString();
            txtAge.Text = student["student_age"].ToString();
            txtScore.Text = student["student_score"].ToString();

            cboColleges.SelectedValue = student["college_id"];

        }

        private void btnnew_Click(object sender, EventArgs e)
        {
            txtId.Text = string.Empty;
            txtName.Text = string.Empty;
            txtAge.Text = string.Empty;
            txtScore.Text = string.Empty;
        }

        private void btnInsert_Click(object sender, EventArgs e)
        {
            DataRow newStudent = students.NewRow();

            newStudent["student_id"] = txtId.Text;
            newStudent["student_name"] = txtName.Text;
            newStudent["student_age"] = txtAge.Text;
            newStudent["student_score"] = txtScore.Text;

            students.Rows.Add(newStudent);
        }

        private void btnUpdate_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(txtId.Text))
            {
                return;
            }

            listStudent.SelectedIndexChanged -= listStudent_SelectedIndexChanged;

            DataRow oldStudent = students.Rows.Find(txtId.Text);

            oldStudent["student_id"] = txtId.Text;
            oldStudent["student_name"] = txtName.Text;
            oldStudent["student_age"] = txtAge.Text;
            oldStudent["student_score"] = txtScore.Text;

            if (cboColleges.SelectedIndex >= 0)
            {
                oldStudent["college_id"] = cboColleges.SelectedValue;
            }
            listStudent.SelectedIndexChanged += listStudent_SelectedIndexChanged;
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            SqlConnection connection = new SqlConnection(connectionString);

            string selectCommand = "select * from student";

            SqlCommand command = new SqlCommand();
            //command.CommandText = "select * from student";
            command.CommandText = selectCommand;
            command.Connection = connection;
            //适配器
            SqlDataAdapter studentAdapter = new SqlDataAdapter();
            studentAdapter.SelectCommand = command;
            //
            SqlCommandBuilder studentCommandBuilder = new SqlCommandBuilder();
            studentCommandBuilder.DataAdapter = studentAdapter;

            studentAdapter.Update(students);
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(txtId.Text))
            {
                return;
            }
            DataRow oldStudent = students.Rows.Find(txtId.Text);
            oldStudent.Delete();
        }

        private void cboColleges_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cboColleges.SelectedIndex < 0)
            {
                return;
            }

            DataRow college = colleges.Rows.Find(cboColleges.SelectedValue);

            string s = string.Empty;

            foreach(var item in college.GetChildRows(dataSet.Relations["FK_student_college"]))
            {
                s += item["student_id"] + "\t" + item["student_name"];
            }
            rtxtStudentList.Text = s;
        }
    }
}
//单表改

 整体效果

源码下载:

链接:https://pan.baidu.com/s/1AksyhybGOjPy_3sgX_YqYw
提取码:5ae1

用我的代码 改一下数据库连接字符串即可。仍有问题可以私信我,看到就回~

你可能感兴趣的:(C#,数据库原理,c#,sqlserver,visual,studio,数据库)