分享

C#如何在textBox上显示数据库文本并且可以进行修改

 昵称48397323 2017-10-15
我帮你写了个,说的很详细,还有不懂再提出来。我用的是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,点击姓名查询将查到的结果显示在后面,修改为按钮,你在后面的文本框输入要改成的名字,再点按钮,就修改了。 觉得不好再提出,一起学习下,呵呵

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多