数据库方面的设置
你需要新建一个test数据库,在里面新建一个Student表,表里要有StudentName这一列,在里面插入你想写入的数据。这些工作做完才可以用到我后面的代码。
关于数据库代码插入删除数据见打开Sql Server代码编辑器及相关操作的文章
控件设计
程序代码
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 WindowsFormsApp20
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
//使用try...catch语句返回try代码区异常
try
{
//创建数据库连接并打开
string ConString = "server=.;database=test;uid=sa;pwd=sa;";
SqlConnection ConStudent = new SqlConnection(ConString);
string CmdString = string.Format($"select * from Student " +
$"where " +
$"StudentName like '%{textBox1.Text.Trim()}%'");
//也就是说你在数据库test下面里一个Student的表
//like和%%用来支持模糊查询
SqlCommand cmdStudent = new SqlCommand(CmdString, ConStudent);
ConStudent.Open();
//创建读取对象SqlDataReader
SqlDataReader dtrStudent = cmdStudent.ExecuteReader();
textBox2.Text = "学号\t\t姓名\t\t性别\t\t专业\r\n";
//使用HasRows属性判断数读取的dtrStudent对象中是否有数据
if(dtrStudent.HasRows)
{
//从dtrStudent中一条一条读取数据
while(dtrStudent.Read())
{
textBox2.Text += string.Format($"{dtrStudent[0].ToString()}\t" +
$"{dtrStudent[1].ToString()}\t{dtrStudent[2].ToString()}\t" +
$"{dtrStudent[3].ToString()}\r\n");
}
}
else
{
MessageBox.Show("查无此人!");
}
dtrStudent.Close();
ConStudent.Close();
}
//返回异常
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
}