C#基础知识及题目练习 Day24 ADO.NET 连接数据库 显示在ListView中 实现增删改

目录

一、列表视图控件ListView

二、ADO.NET操作数据库——增删改

(一)ListView控件的Click事件:

(二)增删改数据库步骤:

eg:实现作者的增删改与listview显示


一、列表视图控件ListView

1.属性:

FullRowSelect:选中一项时,它的子项是否同该项一起突出显示

MultiSelect :是否允许选择多项

Items:控件中所有项的集合

SelectedItems :选中项的集合

Columns:Detail视图中显示的项

View:指定控件的视图模式LargeIcon(大图标)、SmallIcon(小图标)、List(列表)、Detail(详细信息)、Title(平铺)

2.操作:

SqlDataReader allFile = com.ExecuteReader();

while (allFile.Read()) //循环读取查询结果的每一行

{

    //在读取的每一行里通过列名取出5列的值

    string fName = (string)allFile["FName"];

    string fTime = allFile["FTime"].ToString();

    ……

   //创建一个ListView中的项,此项的第一个显示项是下载的文件名

    ListViewItem lviFName = new ListViewItem(fName);

    //在创建的ListView项的子项集合中添加其余的4个显示项(大小,进度,类型,开始时间)

    lviFName.SubItems.AddRange(new string[] { fSize, fPlan, fType, fTime });

    //把这个ListView项添加到窗体的ListView控件的项集合中

    lvDownload.Items.Add(lviFName);

}……

二、ADO.NET操作数据库——增删改

1.增加数据(Insert)

//添加SQL语句

string strsql = "insert into MasterFollowerInfo values('"+name+"',"+age+",'"+status+"','"+power+"')";

SqlCommand com = new SqlCommand(strsql,con);

con.Open();   //打开连接

int count = com.ExecuteNonQuery(); //执行添加,返回添加行数

if (count > 0)  //判断添加是否成功 ……

con.Close();  //关闭数据库的连接

2.修改数据(Update)

//更新SQL语句

string strsql = "update MasterFollowerInfo set age=" + age + ",Status='" + status + "',MPower='" + power + "' where Mname='"+name+"'";

SqlCommand com = new SqlCommand(strsql,con);

con.Open();   //打开连接

int count = com.ExecuteNonQuery(); //执行更新,返回更新行数

if (count > 0)  //判断更新是否成功 ……

con.Close();  //关闭数据库的连接

3.删除数据(Delete)

//删除SQL语句

string strsql = "delete from MasterFollowerDB where Mname='" + name + "'";

SqlCommand com = new SqlCommand(strsql,con);

con.Open();   //打开连接

int count = com.ExecuteNonQuery(); //执行删除返回删除行数

if (count > 0)  //判断删除是否成功 ……

con.Close();  //关闭数据库的连接

 

(一)ListView控件的Click事件:

//把选中项的索引保存住

selectIndex = lvPatients.SelectedItems[0].Index;

//循环所有下拉列表的项

for (int i = 0; i < cboSOffice.Items.Count; i++)

{

    //判断每一项内容是否和选中项的医科相同

    if (cboSOffice.Items[i].ToString() == lvPatients.SelectedItems[0].SubItems[3].Text.Trim())

        cboSOffice.SelectedIndex = i; //如果相同,在下拉列表里显示这一项

}

1).修改按钮事件

int count = com.ExecuteNonQuery();  //执行修改

if (count > 0)   //判断修改是否成功

{

    //修改成功后从列表视图控件中修改选中项的值

    lvPatients.Items[selectIndex].SubItems[1].Text = age.ToString();

    lvPatients.Items[selectIndex].SubItems[2].Text = sex;

    ……

    MessageBox.Show("修改成功!");

}

2).删除按钮事件

int count = com.ExecuteNonQuery();   //执行删除

if (count > 0) //判断删除是否成功

{

    //删除成功后从列表视图控件中清除选中项

    lvPatients.Items.RemoveAt(selectIndex);

    MessageBox.Show("删除成功!");

}

作数据库步骤

(二)增删改数据库步骤:

  • 第一步,创建Connection连接对象。
  • 第二步,保存增、删、改的SQL语句。
  • 第三步,创建Command对象。
  • 第四步,打开数据库连接。
  • 第五步,执行增、删、改操作,接受返回的影响行数。
  • 第六步,关闭数据库连接。

 

ListView控件绑定DataTable的方法:

实现绑定控件的column的属性,再进行item的绑定

https://blog.csdn.net/pp_fzp/article/details/50709566

 

eg:实现作者的增删改与listview显示

    public partial class Form1 : Form
    {
        //string sqlStr = "data source=.;initial catalog=Hero;user id=sa;pwd=admin123";
        string sqlStr = "server=.;database=Hero;user id=sa;pwd=admin123";   //1、创建连接字符串
        List<MyAuthor> lstAuthors = new List<MyAuthor>();   //存储所有作者信息

        public Form1()
        {
            InitializeComponent();

            //更改生日控件的显示样式   2019-01-01
            dateTimePicker1.Format = DateTimePickerFormat.Custom;
            dateTimePicker1.CustomFormat = "yyyy-MM-dd";
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            try
            {
                //2、创建数据库连接对象
                SqlConnection con = new SqlConnection(sqlStr);
                //3、打开数据库连接
                con.Open();
                toolStripStatusLabel1.Text = "数据库已连接...";

                //4、创建SqlCommand对象
                SqlCommand cmd = new SqlCommand();

                //5、赋值Connection属性
                cmd.Connection = con;

                //6、获取控件上的值
                string name = txtName.Text.Trim();  //姓名
                string age = txtAge.Text.Trim();    //年龄
                string city = combCity.Text.Trim(); //居住地
                string email = txtEmail.Text.Trim(); //邮箱
                string birthday = dateTimePicker1.Text; //生日
                int sex = radioMan.Checked == true ? 1 : 0;   //性别
                string Tel = txtTel.Text.Trim();    //电话

                //7、编写sql语句
                string sql = string.Format("insert into Authors values('{0}',{1},'{2}','{3}',{4},'{5}',{6})",
                    name, sex, birthday, email, Tel, city, age);
                //8、赋值给COmmndText
                cmd.CommandText = sql;

                //9、调用方法,执行COmmand命令
                int n = cmd.ExecuteNonQuery();
                if (n > 0)
                {
                    //在执行sql语句的内部,尽量不要使用MessageBox,因为如果对话框不关闭的
                    //话,其他用户没有办法访问该数据表。该操作时排他的。
                    toolStripStatusLabel3.Text = "     数据插入成功!!";
                }
                else
                {
                    toolStripStatusLabel3.Text = "    数据插入失败!请检查原因!!!";
                }

                //10、关闭连接
                con.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        /// <summary>
        /// 从数据库中查询并显示所有作者
        /// </summary>
        private void ShowAllAuthors()
        {
            //清空ListView中的现有项
            listView1.Items.Clear();
            try
            {
                //0、创建作者对象

                //使用using将Connection包裹起来,可以省掉关闭的麻烦
                using (SqlConnection con=new SqlConnection(sqlStr))
                {
                    //1、打开数据库连接
                    con.Open();

                    //2、创建SqlCommnd对象
                    SqlCommand cmd = new SqlCommand();
                    //3、赋值Connection对象
                    cmd.Connection = con;
                    //4、编写sql,赋值CommondText对象
                    string sql = "select * from Authors";
                    cmd.CommandText = sql;
                    //5、执行Command命令,返回DataReader队形
                    using (SqlDataReader reader = cmd.ExecuteReader())
                    {
                        //有几句话:1)reader对象在读取数据的过程中,数据库连接要始终保持,直到
                        //所有数据都读取完才能关闭。
                        //2)、只读,只进。它只能读取数据,不能修改数据;只能前进,不能后退。
                        //3)、默认情况下,DataReader独占一个连接对象。

                        //使用Reader对象,读取数据库中的数据,并存到类对象中
                        //判断一下查询是否有结果
                        if (reader.HasRows)
                        {
                            while (reader.Read())
                            {
                                MyAuthor auth = new MyAuthor();
                                auth.AuthorId = reader["AuthorId"].ToString();   //作者编号
                                auth.AuthorName = reader["AuthorName"].ToString();    //作者姓名
                                auth.City = reader["City"].ToString();  //居住地
                                auth.Email = reader["Email"].ToString(); //邮箱
                                auth.Sex = reader["Sex"].ToString();   //性别
                                auth.Tel = reader["Telephone"].ToString();   //电话
                                auth.BirthDay = reader["Birthday"].ToString();  //生日
                                auth.Age = reader["Age"].ToString();    //年龄
                                //6、将该作者信息添加ListView控件中
                                //6-1:创建ListVIewItem,将要显示的第一列赋值给该对象
                                ListViewItem item = new ListViewItem(auth.AuthorId);
                                //6-2:添加其他列
                                item.SubItems.Add(auth.AuthorName);
                                item.SubItems.Add(auth.City);
                                string[] arr = { auth.Email, auth.Sex, auth.Tel, auth.BirthDay, auth.Age };
                                item.SubItems.AddRange(arr);
                                //6-3:将该ListViewItem添加到ListView控件中
                                listView1.Items.Add(item);
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                throw;
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            ShowAllAuthors();
        }

        private void btnModify_Click(object sender, EventArgs e)
        {
            //判断是否选中项
            if (txtId.Text == "")
            {
                MessageBox.Show("请选中一行进行修改!");
                return;
            }
            if (txtName.Text == "")
            {
                MessageBox.Show("作者不能为空,请确认!");
                return;
            }

            //从控件上取出已经修改好的值,然后更新回数据库
            string name = txtName.Text.Trim();  //姓名
            string City = combCity.Text;    //居住地
            string Email = txtEmail.Text.Trim();    //邮箱
            string sex = radioMan.Checked ? "1" : "0";  //性别
            string Tel = txtTel.Text.Trim();    //电话
            string Birth = dateTimePicker1.Text;    //生日
            string Age = txtAge.Text.Trim();    //年龄

            using (SqlConnection con=new SqlConnection(sqlStr))
            {
                //打开连接
                con.Open();
                //编写sql语句
                string sql = string.Format("update Authors set AuthorName='{0}',City='{1}',Email='{2}',Sex={3},Telephone='{4}',Birthday='{5}',Age={6} where AuthorId={7}",
                    name, City, Email, sex, Tel, Birth, Age,txtId.Text);
                //创建Command对象
                SqlCommand cmd = new SqlCommand(sql, con);

                //执行Command命令
               int n= cmd.ExecuteNonQuery();
                if (n > 0)
                {
                    //在执行sql语句的内部,尽量不要使用MessageBox,因为如果对话框不关闭的
                    //话,其他用户没有办法访问该数据表。该操作时排他的。
                    toolStripStatusLabel3.Text = "     数据修改成功!!";
                }
                else
                {
                    toolStripStatusLabel3.Text = "    数据修改失败!请检查原因!!!";
                }
            }
            //更新数据源
            ShowAllAuthors();
        }
    }

1.更改生日控件的显示样式   2019-01-01
            dateTimePicker1.Format = DateTimePickerFormat.Custom;
            dateTimePicker1.CustomFormat = "yyyy-MM-dd";

2.在执行sql语句的内部,尽量不要使用MessageBox,因为如果对话框不关闭的话,其他用户没有办法访问该数据表。

该操作是排他的。

3.使用using将Connection包裹起来,可以省掉关闭的麻烦

4.reader对象

1)reader对象在读取数据的过程中,数据库连接要始终保持,直到所有数据都读取完才能关闭。
2)reader对象只读,只进。它只能读取数据,不能修改数据;只能前进,不能后退。
3)默认情况下,DataReader独占一个连接对象。

5.创建ListVIewItem,将要显示的第一列赋值给该对象
ListViewItem item = new ListViewItem(auth.AuthorId);

6.StatusStrip状态栏控件

StatusStripStatuslabel,作用就是使用文本和图像用户显示应用程序当前状态的信息。

 

eg:书籍管理:

//点击添加
        private void btnAdd_Click(object sender, EventArgs e)
        {
            //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();

            //创建一个新的书籍对象
            //BooksInStore bookNew = new BooksInStore(bookNum,bookName,bookAuthor,bookCategory,bookIntro,bookImagePath,bookPath,bookPrice);

        }

        //从数据库中查询并显示到listview中
        private void ShowAllBooks()
        {
            //清空ListView中的现有项
            listView1.Items.Clear();
            try
            {
                using (SqlConnection con = new SqlConnection(strCon))
                {
                    con.Open();
                    toolStripStatusLabel1.Text = "数据库已连接...";
                    SqlCommand cmd = new SqlCommand();
                    cmd.Connection = con;
                    //4、编写sql,赋值CommondText对象
                    string sql = "select * from Bookstore";
                    cmd.CommandText = sql;
                    //5、执行Command命令,返回DataReader对象
                    using (SqlDataReader reader = cmd.ExecuteReader())
                    {
                        //使用Reader对象,读取数据库中的数据,并存到类对象中
                        if (reader.HasRows)//判断一下查询是否有结果
                        {
                            while (reader.Read())//循环读取每一行
                            {
                                //获取每一列的值
                                int id = (int)reader["bookID"];
                                string name = reader["bookName"].ToString();
                                string author = reader["Author"].ToString();
                                string category = reader["Category"].ToString();
                                string intro = reader["Intro"].ToString();
                                string imgPath = reader["imgPath"].ToString();
                                string txtPath = reader["txtPath"].ToString();
                                double price = (double)reader["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 void btnDel_Click(object sender, EventArgs e)
        {
            //判断是否选中项
            if (txtNum.Text == "")
            {
                MessageBox.Show("请选中一行进行修改!");
                return;
            }
            if (txtName.Text == "")
            {
                MessageBox.Show("作者不能为空,请确认!");
                return;
            }
            if (txtPath.Text == "")
            {
                MessageBox.Show("文件路径不能为空,请确认!");
                return;
            }
            using (SqlConnection con = new SqlConnection(strCon))
            {
                con.Open();
                toolStripStatusLabel1.Text = "数据库已连接...";
                SqlCommand cmd = new SqlCommand();
                cmd.Connection = con;
                //4、编写sql,赋值CommondText对象
                string sql = string.Format("DELETE FROM Bookstore where bookID={0}", txtNum.Text);
                cmd.CommandText = sql;
                int n = cmd.ExecuteNonQuery();
                if (n > 0)
                {
                    toolStripStatusLabel1.Text = "数据删除成功!!";
                }
                else
                {
                    toolStripStatusLabel1.Text = "数据删除失败...";
                }
                //更新数据源
                ShowAllBooks();
            }
        }

        //点击确定
        private void btnYes_Click(object sender, EventArgs e)
        {

        }

        private void listView1_Click(object sender, EventArgs e)
        {
            if (listView1.SelectedItems.Count > 0)
            {
                //当前选中行的第一列的值
                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;
                }
            }
        }

 

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值