c#开发学习之listview连接SQLserver并将数据放到listview里显示

using System;
using System.Collections.Generic;
using System.ComponentModel;
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 Wpf
{
    public partial class UserCRUDForm : Form
    {
        public UserCRUDForm()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {

            try
            {
                showdata();

            } catch (Exception ex) {
                MessageBox.Show(ex.Message);

            }
        }

        private void showdata()
        {
            listView1.Items.Clear();
            listView1.Columns.Clear();
            //编辑表头
            listView1.Columns.Add("编号");
            listView1.Columns.Add("姓名");
            listView1.Columns.Add("密码");
string conn = "server=.;database=test" + ";uid=sa;password=3044136609"; SqlConnection sqlcon = new SqlConnection(conn);
string sql = "select * from 管理员"; SqlDataAdapter sqlda = new SqlDataAdapter(sql, sqlcon);
DataSet ds
= new DataSet(); sqlda.Fill(ds);
string[] str=new string[1000]; foreach (DataRow dr in ds.Tables[0].Rows) { str[0] = dr["id"].ToString(); str[1] = dr["name"].ToString(); str[2] = dr["password"].ToString(); //listview的第一列可以认为就是item.Subitenms[0] ListViewItem item = new ListViewItem(str[0]); item.SubItems.Add(str[1]); item.SubItems.Add(str[2]); listView1.Items.Add(item); } } private void button2_Click(object sender, EventArgs e) { try { deletedata(); }catch(Exception ex) { MessageBox.Show(ex.Message); } } private void deletedata() { //数据库连接操作 string conn = "server=.;database=test" + ";uid=sa;password=3044136609"; SqlConnection sqlcon = new SqlConnection(conn);
//获取一行的各列值,以后可以将这些列值封装到实体类 string id = listView1.SelectedItems[0].SubItems[0].Text; string name = listView1.SelectedItems[0].SubItems[1].Text; MessageBox.Show(id + " " + name);
string sql = "delete from 管理员 where id="+id+";"; //数据库打开操作 sqlcon.Open(); //实例化sqlcommand对象 SqlCommand cmd=new SqlCommand(sql, sqlcon);
int num=cmd.ExecuteNonQuery(); if(num > 0) { MessageBox.Show("删除成功"); showdata(); } } } }

 

posted @ 2023-09-29 19:56  cojames  阅读(193)  评论(0编辑  收藏  举报