标签:hid closed elf 实体 连接字符串 image new space div
说明:通过DataAdapter或者dataset连接数据库,实现对数据增删改查操作.
以前写过一篇步步为营-23-通过GridView实现增删改
1:SqlDataAdapter DataTable实现
using System; using System.Collections.Generic; using System.ComponentModel; using System.Configuration; using System.Data; using System.Data.SqlClient; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace DataView { public partial class MainForm : Form { public MainForm() { InitializeComponent(); } private void MainForm_Load(object sender, EventArgs e) { //01-创建配置文件 添加引用 //02-设置连接字符串] string connStr = ConfigurationManager.ConnectionStrings["connStr"].ConnectionString; //03 创建连接字符串 using (SqlConnection conn = new SqlConnection(connStr)) { //04-创建数据库操作脚本 string sqlStr = "select EmpId, Pwd, StuName, StuAge, Delflag, ClassNo from UserInfo"; using (SqlDataAdapter sda = new SqlDataAdapter(sqlStr,conn)) { //05-隆重介绍一下Adapter-适配器 //05-01判断sqlConnection是否初始化 //05-02初始化Select Command对象 //05-03 通过cmd对象执行返回SQLdataReader对象 //05-04 读取数据,填充到datatreader上 DataTable dt = new DataTable(); sda.Fill(dt); //05-创建实体模型,对数据进行封装 List<UserINfo> userList = new List<UserINfo>(); foreach (DataRow dataRow in dt.Rows) { //封装数据 userList.Add(new UserINfo() { EmpId = int.Parse(dataRow["EmpId"].ToString()), StuName = dataRow["StuName"].ToString(), StuAge = int.Parse(dataRow["StuAge"].ToString()) }); } //06-设置数据源 this.dataGridView1.DataSource = userList; } } } } }
2:运行效果
3SqlDataAdapter DataSet实现
using System; using System.Collections.Generic; using System.ComponentModel; using System.Configuration; using System.Data; using System.Data.SqlClient; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace DataView { public partial class MainForm : Form { public MainForm() { InitializeComponent(); } private void MainForm_Load(object sender, EventArgs e) { //01-创建配置文件 添加引用 //02-设置连接字符串] string connStr = ConfigurationManager.ConnectionStrings["connStr"].ConnectionString; //03 创建连接字符串 using (SqlConnection conn = new SqlConnection(connStr)) { //04-创建数据库操作脚本 string sqlStr = @" select ClassId, ClassName from ClassInfo; select EmpId, Pwd, StuName, StuAge, Delflag, ClassNo from UserInfo"; using (SqlDataAdapter sda = new SqlDataAdapter(sqlStr,conn)) { //05-隆重介绍一下Adapter-适配器 //05-01判断sqlConnection是否初始化 //05-02初始化Select Command对象 //05-03 通过cmd对象执行返回SQLdataReader对象 //05-04 读取数据,填充到datatreader上 DataSet ds = new DataSet(); sda.Fill(ds); List<UserINfo> userList = new List<UserINfo>(); foreach (DataRow dataRow in ds.Tables[1].Rows) { //封装数据 userList.Add(new UserINfo() { EmpId = int.Parse(dataRow["EmpId"].ToString()), StuName = dataRow["StuName"].ToString(), StuAge = int.Parse(dataRow["StuAge"].ToString()) }); } this.dataGridView1.DataSource = userList; } } } } }
标签:hid closed elf 实体 连接字符串 image new space div
原文地址:http://www.cnblogs.com/YK2012/p/6781414.html