使用DataAdapter把数据库数据填充到DataSet并把修改的数据更新到数据库、数据显示控件DataGridView

一、数据集对象DataSet

驻留于内存,临时存储数据。

简单理解为一个临时数据库,将数据源的数据保存在内存中,独立于任何数据库。

 

----在CensorForm窗体的Load事件里实现添加数据的代码:

DataTable table = new DataTable(); //创建表对象

//添加表的列结构(列名,数据类型),共添加4列

table.Columns.Add("姓名", Type.GetType("System.String"));

//用表对象创建一个数据行对象,数据行对象的列结构和表对象一样

DataRow row = table.NewRow();

row["姓名"] = "唐僧";   //给这个数据行的4个列赋值

table.Rows.Add(row); //把这个数据行添加到表对象的行集合中

allInfo.Tables.Add(table); //把表对象添加到数据集的表集合中

 

二、适配器对象DataAdapter--如何将数据库的数据放在 DataSet 中
1.属性和方法:

属性

说明

SelectCommand

从数据库查询数据的Command对象

方法

说明

Fill()

从数据库查询数据并填充到DataSet对象的表中

Update()

将DataSet对象中的数据保存回数据库中

 

2.通过DataAdapter对象填充DataSet

DataSet allPatient = new DataSet();  //创建DataSet对象

SqlDataAdapter adapter; //声明DataAdapter对象

//窗体加载事件

private void PatientInfoForm_Load(object sender, EventArgs e)

{

    string strsql = "select * from MovieInfo";

    adapter = new SqlDataAdapter(strsql,con);//Strsql是查询SQL语句,con是连接对象

    //查询并填充DataSet对象

    adapter.Fill(allPatient,"PatientInfo");//PatientInfo是临时表名,可以和数据库表名不同

}

3.把DataSet中的数据保存回数据库

1.在DataSet的DataTable中添加一行数据
DataRow row = DataSet对象.Tables[“表名"].NewRow();

row[“列名”] = 值;

或删除DataSet中的选中行 :

DataSet对象.Tables[“表名”].Rows[行索引].Delete();

2.创建SqlCommandBuilder对象
SqlCommandBuilder builder = new SqlCommandBuilder(DataAdapter对象);

3.使用DataAdapter对象的Update()方法执行更新
        DataAdapter对象.Update(DataSet对象, “表名");

eg:

DataRow row = allMovies.Tables["MovieInfo"].NewRow();

//给数据行的各列赋值

row["PName"] = name;

//把新创建的数据行添加到数据集的数据表中

allMovies.Tables["MovieInfo"].Rows.Add(row);

//创建自动进行保存功能的CommandBuilder对象

SqlCommandBuilder builder = new SqlCommandBuilder(adapter);

adapter.Update(allPatient, “PatientInfo”);  //把数据集中PatientInfo表的所有数据更新回数据库

 

三、数据显示控件DataGridView
1.属性:

 

 

2.在DataGridView中显示数据:

string strsql = "select * from PatientInfo";

adapter = new SqlDataAdapter(strsql, con);

//查询并填充DataSet对象

adapter.Fill(allPatient,"PatientInfo");

//指定DataGridView控件的数据源是DataSet中的PatientInfo表

dgvPatients.DataSource = allPatient.Tables["PatientInfo"];

2.鼠标双击单元格直接修改此单元格内数据

//创建自动进行保存功能的CommandBuilder对象

SqlCommandBuilder builder = new SqlCommandBuilder(adapter);

//把数据集中PatientInfo表的数据更新回数据库

adapter.Update(allPatient, "PatientInfo");

 

eg1:使用ListView

    public partial class Form1 : Form
    {
        //创建连接对象
        SqlConnection con = new SqlConnection("data source=.;initial catalog=test;user id=sa;pwd=admin123");
        DataSet allMovies = new DataSet();//创建DataSet对象
        //创建DataAdapter对象
        SqlDataAdapter adapter;
        int nSelectedIndex = -1;    //当前选中项的下标
        public Form1()
        {
            InitializeComponent();
        }
        private void Form1_Load(object sender, EventArgs e)
        {
            //保存查询语句
            string strsql = "select * from MovieInfo";
            //创建DataAdapter对象
            adapter = new SqlDataAdapter(strsql, con);
            //查询并填充DataSet对象
            adapter.Fill(allMovies, "MovieInfo");
            //循环从数据集的表集合中的第一个表的行集合中每次得到一个行对象
            foreach(DataRow row in allMovies.Tables[0].Rows)
            {
                string name = row["MovieName"].ToString();
                string type = row["MovieType"].ToString();
                string leader = row["MovieCompany"].ToString();
                string rank = row["Rank"].ToString();
                //创建列表视图显示项,把值添加到显示项中
                ListViewItem lviItem = new ListViewItem(name);
                lviItem.SubItems.AddRange(new string[] { type, leader, rank });
                //把显示项添加到列表视图控件的项集合中
                lviMovie.Items.Add(lviItem);
            }
        }
 
        //验证非空的自定义方法
        private bool CheckInfo()
        {
            bool b = true;
            if (txtName.Text.Trim() == "" || txtLeader.Text.Trim() == "" || cmbType.Text.Trim() == "" || txtRank.Text.Trim() == "")
            {
                MessageBox.Show("请输入完整信息!");
                b = false;
            }
            return b;
        }
        /// <summary>
        /// 添加新上映电影
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnAdd_Click(object sender, EventArgs e)
        {
            bool b = CheckInfo();   //调用自定义方法
            if (b == false) //判断验证是否通过
            {
                return;
            }
            try
            {
                //保存电影信息
                string name = txtName.Text.Trim();
                string type = cmbType.Text.Trim();
                string leader = txtLeader.Text.Trim();
                string rank = txtRank.Text.Trim();
                //创建同数据集的数据表结构相同的数据行对象
                DataRow row = allMovies.Tables["MovieInfo"].NewRow();
                row["MovieName"] = name;
                row["MovieType"] = type;
                row["MovieCompany"] = leader;
                row["Rank"] = rank;
                //把新创建的数据行添加到数据集的数据表中
                allMovies.Tables["MovieInfo"].Rows.Add(row);
                //创建自动进行保存功能的CommandBuilder对象
                SqlCommandBuilder builder = new SqlCommandBuilder(adapter);
                //把数据集中MovieInfo表的数据更新回数据库
                adapter.Update(allMovies, "MovieInfo");
                //把信息显示在列表视图控件里
                ListViewItem item = new ListViewItem(name);
                item.SubItems.AddRange(new string[] { type, leader, rank });
                lviMovie.Items.Add(item);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        /// <summary>
        /// 修改电影信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnMody_Click(object sender, EventArgs e)
        {
            bool b = CheckInfo(); //调用自定义方法
            if (b == false)//判断验证是否通过
            {
                return;//结束保存
            }
            if (nSelectedIndex < 0)
            {
                MessageBox.Show("未选中任何行,请选中一行进行修改","警告");
                return;
            }
            try
            {
                //保存电影信息
                string name = txtName.Text.Trim();
                string type = cmbType.Text.Trim();
                string leader = txtLeader.Text.Trim();
                string rank = txtRank.Text.Trim();
                //修改DataSet中选中行对应的数据表的各列数据
                allMovies.Tables["MovieInfo"].Rows[nSelectedIndex]["MovieName"] = name;
                allMovies.Tables["MovieInfo"].Rows[nSelectedIndex]["MovieType"] = name;
                allMovies.Tables["MovieInfo"].Rows[nSelectedIndex]["MovieCompany"] = name;
                allMovies.Tables["MovieInfo"].Rows[nSelectedIndex]["Rank"] = name;
                //创建自动进行保存功能的CommandBuilder对象
                SqlCommandBuilder builder = new SqlCommandBuilder(adapter);
                //把数据集中MovieInfo表的数据更新回数据库
                adapter.Update(allMovies, "MovieInfo");
                //修改ListView控件中选中行的各列数据
                lviMovie.Items[nSelectedIndex].SubItems[0].Text = name;
                lviMovie.Items[nSelectedIndex].SubItems[1].Text = type;
                lviMovie.Items[nSelectedIndex].SubItems[2].Text = leader;
                lviMovie.Items[nSelectedIndex].SubItems[3].Text = rank;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
 
        private void lviMovie_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (lviMovie.SelectedItems.Count <= 0) return;
            if (lviMovie.SelectedItems != null)
            {
                nSelectedIndex = lviMovie.SelectedItems[0].Index;
                txtName.ReadOnly = true;
                txtName.Text = lviMovie.SelectedItems[0].Text;
                cmbType.Text = lviMovie.SelectedItems[0].SubItems[1].Text;
                txtLeader.Text = lviMovie.SelectedItems[0].SubItems[2].Text;
                txtRank.Text = lviMovie.SelectedItems[0].SubItems[3].Text;
 
            }
        }
        /// <summary>
        /// 删除电影信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnDel_Click(object sender, EventArgs e)
        {
            if (lviMovie.SelectedItems.Count <= 0)
            {
                MessageBox.Show("请选中一行进行删除。");
                return;
            }
            try
            {
                DialogResult result = MessageBox.Show("确定要删除该条记录吗?", "询问", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1);
                if (result == DialogResult.No) return;
                //在DataSet中删除选中行
                allMovies.Tables["MovieInfo"].Rows[nSelectedIndex].Delete();
                //创建自动进行保存功能的CommandBuilder对象
                SqlCommandBuilder builder = new SqlCommandBuilder(adapter);
                //把数据集中MovieInfo表的数据更新回数据库
                adapter.Update(allMovies, "MovieInfo");
                //删除成功后从列表视图控件中清除选中项
                lviMovie.Items.RemoveAt(nSelectedIndex);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
    }

eg2:使用datagridview:

    public partial class Form1 : Form
    {
        //创建连接对象
        SqlConnection con = new SqlConnection("data source=.;initial catalog=test;user id=sa;pwd=admin123");
        DataSet allMovies = new DataSet();//创建DataSet对象
        //创建DataAdapter对象
        SqlDataAdapter adapter;
        public Form1()
        {
            InitializeComponent();
        }
        private void Form1_Load(object sender, EventArgs e)
        {
            //保存查询语句
            string strsql = "select * from MovieInfo";
            //创建DataAdapter对象
            adapter = new SqlDataAdapter(strsql, con);
           // allMovies.Tables["MovieInfo"].PrimaryKey = new DataColumn[] { allMovies.Tables["MovieInfo"].Columns["id"] };
            //查询并填充DataSet对象
            adapter.Fill(allMovies, "MovieInfo");
            //指定DataGridView控件的数据源是DataSet中的PatientInfo表
            dgvMovies.DataSource = allMovies.Tables["MovieInfo"];
        }
        private void toolStripButton2_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }
        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            //创建自动进行保存功能的CommandBuilder对象
            SqlCommandBuilder builder = new SqlCommandBuilder(adapter);
            //把数据集中PatientInfo表的数据更新回数据库 
            //*****运用这种方式,必须为表指定主键,或者手动写update sql
            adapter.Update(allMovies, "MovieInfo");
            //指定DataGridView控件的数据源是DataSet中的PatientInfo表
            dgvMovies.DataSource = allMovies.Tables["MovieInfo"];
        }
    }

使用listView的备份:

public partial class AdminManage : Form
    {
        //1.数据库连接字符串
        string strCon = "data source=.;database=Bookview;user id=sa;pwd=machenxi";
        int selectIndex=-1;//保存列表视图控件中选中项的索引
        DataSet allPatient = new DataSet();//创建DataSet对象
        //创建DataAdapter对象
        SqlDataAdapter adapter;
 
        //书籍集合,存储所有书籍信息
        List<BooksInStore> lstB = new List<BooksInStore>();
 
        //窗体加载事件
        public AdminManage()
        {
            InitializeComponent();
            
            ShowAllBooks();
        }
        //点击添加
        private void btnAdd_Click(object sender, EventArgs e)
        {
            if (CheckInfo() == false)//判断验证是否通过
            {
                return;//结束保存
            }
            //2、创建数据库连接对象
            SqlConnection con = new SqlConnection(strCon);
            //3、打开数据库连接
            con.Open();
            toolStripStatusLabel1.Text = "数据库已连接...";
            //4、创建SqlCommand对象
            SqlCommand cmd = new SqlCommand();
            //5、赋值Connection属性
            cmd.Connection = con;
            //6、获取控件上输入的书籍名称等
            string bookName = txtName.Text.Trim();   //书籍名称
            string bookAuthor = txtAuthor.Text.Trim();   //书籍作者
            string bookPath = txtPath.Text.Trim();   //文件路径
            string bookIntro = txtIntro.Text.Trim();   //书籍简介
            string bookImagePath = txtImagePath.Text.Trim();//封面路径
            string bookCategory = txtCategory.Text.Trim();//类别
            double bookPrice = double.Parse(txtPrice.Text.Trim());//价格
            //7、编写sql语句
            string sql = string.Format("insert into Authors values('{0}','{1}','{2}','{3}',{4},'{5}','{6}',{7},)", bookName, bookAuthor, bookCategory, bookIntro, bookImagePath, bookPath, bookPrice);
            //8、赋值给CommandText
            cmd.CommandText = sql;
            //9、调用方法,执行Command命令
            int n = cmd.ExecuteNonQuery();
            if (n > 0)
            {
                toolStripStatusLabel1.Text = "数据插入成功!!";
            }
            else
            {
                toolStripStatusLabel1.Text = "数据插入失败...";
            }
            ShowAllBooks();
            //10、关闭连接
            con.Close();
 
            创建同数据集的数据表结构相同的数据行对象
            //DataRow r = allPatient.Tables["BookstoreInfo"].NewRow();
            给数据行的各列赋值
            r["bookID"] = bookName;
            //r["bookName"] = bookName;
            //r["Author"] = bookAuthor;
            //r["Category"] = bookCategory;
            //r["Intro"] = bookIntro;
            //r["imgPath"] = bookImagePath;
            //r["txtPath"] = bookPath;
            //r["Price"] = bookPrice;
            把新创建的数据行添加到数据集的数据表中
            //allPatient.Tables["BookstoreInfo"].Rows.Add(r);
            创建自动进行保存功能的CommandBuilder对象
            //SqlCommandBuilder builder = new SqlCommandBuilder(adapter);
            把数据集中PatientInfo表的数据更新回数据库※
            //adapter.Update(allPatient, "BookstoreInfo");
 
        }
 
        //从数据库中查询并显示到listview中
        private void ShowAllBooks()
        {
            //清空ListView中的现有项
            listView1.Items.Clear();
            try
            {
                //保存查询语句
                string strsql = "select * from Bookstore";
                //创建DataAdapter对象
                adapter = new SqlDataAdapter(strsql, strCon);
                //查询并填充DataSet对象
                adapter.Fill(allPatient, "BookstoreInfo");
                //循环从数据集的表集合中的第一个表的行集合中每次得到一个行对象
                foreach (DataRow r in allPatient.Tables[0].Rows)
                {
                    int id = (int)r["bookID"];
                    string name = r["bookName"].ToString();
                    string author = r["Author"].ToString();
                    string category = r["Category"].ToString();
                    string intro = r["Intro"].ToString();
                    string imgPath = r["imgPath"].ToString();
                    string txtPath = r["txtPath"].ToString();
                    double price = (double)r["Price"];
                    BooksInStore b = new BooksInStore(id, name, author, category, intro, imgPath, txtPath, price);
                    //将该类对象添加到集合中
                    lstB.Add(b);
 
                    //将该作者信息添加ListView控件中
                    //创建ListVIewItem,将要显示的第一列赋值给该对象
                    ListViewItem item = new ListViewItem(b.BNum.ToString());
                    //添加其他列
                    string[] arr = { b.BName, b.BAuthor, b.BCategory, b.BIntro, b.BImagePath, b.BPath, b.BPrice.ToString() };
                    item.SubItems.AddRange(arr);
                    //6、3:将该ListViewItem添加到ListView控件中
                    listView1.Items.Add(item);
                }
                toolStripStatusLabel1.Text = "数据已加载...";
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                throw;
            }
        }
 
        //验证非空的自定义方法
        private bool CheckInfo()
        {
            bool b = true;
            if (txtName.Text.Trim() == "" || txtPath.Text.Trim() == "" )
            {
                MessageBox.Show("请输入完整信息!");
                b = false;
            }
            return b;
        }
 
        //点击修改
        private void btnChange_Click(object sender, EventArgs e)
        {
            //判断是否选中项
            if (txtNum.Text == "")
            {
                MessageBox.Show("请选中一行进行修改!");
                return;
            }
            if (CheckInfo() == false)//判断验证是否通过
            {
                return;//结束保存
            }
            
            //从控件上取出已经修改好的值
            string bookName = txtName.Text.Trim();   //书籍名称
            string bookAuthor = txtAuthor.Text.Trim();   //书籍作者
            string bookPath = txtPath.Text.Trim();   //文件路径
            string bookIntro = txtIntro.Text.Trim();   //书籍简介
            string bookImagePath = txtImagePath.Text.Trim();//封面路径
            string bookCategory = txtCategory.Text.Trim();//类别
            double bookPrice = double.Parse(txtPrice.Text.Trim());//价格
            //编写sql语句
            //string sql = string.Format("update Bookstore set BookName='{0}', Author='{1}',Category='{2}', intro='{3}',imgPath='{4}',txtPath='{5}',Price='{6}' where bookID={7}",
            //     bookName, bookAuthor, bookCategory, bookIntro, bookImagePath, bookPath, bookPrice, txtNum.Text);
 
            //修改DataSet中选中行对应的数据表的各列数据
            allPatient.Tables["BookstoreInfo"].Rows[selectIndex]["bookName"] = bookName;
            allPatient.Tables["BookstoreInfo"].Rows[selectIndex]["Author"] = bookAuthor;
            allPatient.Tables["BookstoreInfo"].Rows[selectIndex]["txtPath"] = bookPath;
            allPatient.Tables["BookstoreInfo"].Rows[selectIndex]["Intro"] = bookIntro;
            allPatient.Tables["BookstoreInfo"].Rows[selectIndex]["imgPath"] = bookImagePath;
            allPatient.Tables["BookstoreInfo"].Rows[selectIndex]["txtPath"] = bookPath;
            allPatient.Tables["BookstoreInfo"].Rows[selectIndex]["Price"] = bookPrice;
            //创建自动进行保存功能的CommandBuilder对象
            SqlCommandBuilder builder = new SqlCommandBuilder(adapter);
            //把数据集中PatientInfo表的数据更新回数据库
            adapter.Update(allPatient, "BookstoreInfo");
            //修改ListView控件中选中行的各列数据
            listView1.Items[selectIndex].SubItems[1].Text = bookName;
            listView1.Items[selectIndex].SubItems[2].Text = bookAuthor;
            listView1.Items[selectIndex].SubItems[3].Text = bookCategory;
            listView1.Items[selectIndex].SubItems[4].Text = bookIntro;
            listView1.Items[selectIndex].SubItems[5].Text = bookImagePath;
            listView1.Items[selectIndex].SubItems[6].Text = bookPath;
            listView1.Items[selectIndex].SubItems[7].Text = bookPrice.ToString();
            toolStripStatusLabel1.Text = "数据库修改成功...";
        }
 
        //点击删除
        private void btnDel_Click(object sender, EventArgs e)
        {
            //判断是否选中项
            if (txtNum.Text == "")
            {
                MessageBox.Show("请选中一行进行删除!");
                return;
            }
            //在DataSet中删除选中行
            allPatient.Tables["BookstoreInfo"].Rows[selectIndex].Delete();
            //创建自动进行保存功能的CommandBuilder对象
            SqlCommandBuilder builder = new SqlCommandBuilder(adapter);
            //把数据集中PatientInfo表的数据更新回数据库
            adapter.Update(allPatient, "BookstoreInfo");
            //删除成功后从列表视图控件中清除选中项
            listView1.Items.RemoveAt(selectIndex);
            toolStripStatusLabel1.Text = "数据库已连接...";
        }
 
        //点击确定
        private void btnYes_Click(object sender, EventArgs e)
        {
 
        }
 
        //回显
        private void listView1_Click(object sender, EventArgs e)
        {
            if (listView1.SelectedItems.Count > 0)
            {
                //把选中项的索引保存住
                selectIndex = listView1.SelectedItems[0].Index;
                //当前选中行的第一列的值
                txtNum.Text = listView1.SelectedItems[0].Text;
 
                //此处应该使用类的属性名而不是数据库中的
                if (listView1.SelectedItems[0].SubItems[1] != null) //姓名
                {
                    txtName.Text = listView1.SelectedItems[0].SubItems[1].Text;
                }
                if (listView1.SelectedItems[0].SubItems[2] != null) //作者
                {
                    txtAuthor.Text = listView1.SelectedItems[0].SubItems[2].Text;
                }
                if (listView1.SelectedItems[0].SubItems[3] != null) //类别
                {
                    txtCategory.Text = listView1.SelectedItems[0].SubItems[3].Text;
                }
                if (listView1.SelectedItems[0].SubItems[4] != null) //简介
                {
                    txtIntro.Text = listView1.SelectedItems[0].SubItems[4].Text;
                }
                if (listView1.SelectedItems[0].SubItems[5] != null) //封面地址
                {
                    txtImagePath.Text = listView1.SelectedItems[0].SubItems[5].Text;
                }
                if (listView1.SelectedItems[0].SubItems[6] != null) //文件地址
                {
                    txtPath.Text = listView1.SelectedItems[0].SubItems[6].Text;
                }
                if (listView1.SelectedItems[0].SubItems[7] != null) //价格
                {
                    txtPrice.Text = listView1.SelectedItems[0].SubItems[7].Text;
                }
            }
        }
    }

 

 

 

posted @ 2021-05-22 19:18  清语堂  阅读(896)  评论(0编辑  收藏  举报