C#如何在textBox上显示数据库文本并且可以进行修改
我帮你写了个,说的很详细,还有不懂再提出来。我用的是SQL SERVER数据库,假设数据库名Access,其中有个Name表,表中有id跟name这2列,id为学号name为姓名,C#代码如下:using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Text;using System.Windows.Forms;using System.Data.SqlClient;namespace ConsoleApplication3{ public partial class Form1 : Form { public Form1() { InitializeComponent(); } //连接到数据库 SqlConnection connection = new SqlConnection("Data Source=.;Initial Catalog=Access;Integrated Security=True"); //选择姓名查询按钮发生的事件 private void button1_Click(object sender, EventArgs e) { string sql = string.Format("select name from Name where id={0}",textBox1.Text.Trim()); //查询语句,查询Name表中id等于输入的学号的学生的姓名 connection.Open(); //打开数据库 SqlCommand command = new SqlCommand(sql,connection); // 创建一个SqlCommand对象command对数据库进行操作 SqlDataReader dateReader = command.ExecuteReader(); //用command对象的ExecuteReader()方法来创建一个SqlDataReader对象dateReader dateReader.Read(); //用它的Read()方法来读取查询到的数据 string name =(string)dateReader[0]; //声明一个name变量去接受数据 textBox2.Text = name; // 把查到结果显示在文本框 dateReader.Close(); //关闭查询 connection.Close(); //关闭数据库连接 } //选择修改按钮发生的事件 private void button2_Click(object sender, EventArgs e) { string sql = string.Format("update Name set name={0} where id={1}",textBox3.Text.Trim(),textBox1.Text.Trim()); connection.Open(); SqlCommand command = new SqlCommand(sql,connection); command.ExecuteNonQuery(); //用ExecuteNonQuery()方法对数据进行修改 connection.Close(); } }} 输入学号即数据库中的id,点击姓名查询将查到的结果显示在后面,修改为按钮,你在后面的文本框输入要改成的名字,再点按钮,就修改了。 觉得不好再提出,一起学习下,呵呵
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请
点击举报。