- [DEVEXPRESS] Hỗ trợ tìm kiếm highlight không dấu và không khoảng cách trên Gridview Filter
- [C#] Chia sẻ source code phần mềm Image Downloader tải hàng loạt hình ảnh từ danh sách link url
- [C#] Chụp hình và quay video từ camera trên winform
- [C#] Chia sẽ full source code tách file Pdf thành nhiều file với các tùy chọn
- Giới thiệu về Stock Tracker Widget - Công cụ theo dõi cổ phiếu và cảnh báo giá tăng giảm bằng C# và WPF
- [VB.NET] Chia sẻ công cụ nhập số tiền tự động định dạng tiền tệ Việt Nam
- [VB.NET] Hướng dẫn fill dữ liệu từ winform vào Microsoft word
- [VB.NET] Hướng dẫn chọn nhiều dòng trên Datagridview
- Hướng Dẫn Đăng Nhập Nhiều Tài Khoản Zalo Trên Máy Tính Cực Kỳ Đơn Giản
- [C#] Chia sẻ source code phần mềm đếm số trang tập tin file PDF
- [C#] Cách Sử Dụng DeviceId trong C# Để Tạo Khóa Cho Ứng Dụng
- [SQLSERVER] Loại bỏ Restricted User trên database MSSQL
- [C#] Hướng dẫn tạo mã QRcode Style trên winform
- [C#] Hướng dẫn sử dụng temp mail service api trên winform
- [C#] Hướng dẫn tạo mã thanh toán VietQR Pay không sử dụng API trên winform
- [C#] Hướng Dẫn Tạo Windows Service Đơn Giản Bằng Topshelf
- [C#] Chia sẻ source code đọc dữ liệu từ Google Sheet trên winform
- [C#] Chia sẻ source code tạo mã QR MOMO đa năng Winform
- [C#] Chia sẻ source code phần mềm lên lịch tự động chạy ứng dụng Scheduler Task Winform
- [C#] Hướng dẫn download file từ Minio Server Winform
[C#] Hướng dẫn thêm, xóa, sửa listview sqlserver
Xin chào các bạn, bài viết hôm nay mình chia sẻ các bạn source code lập trình kết nối cơ sở dữ liệu sqlserver sử dụng Listview trên lập trình c#, winform.
[C#] CRUD Sqlserver using Listview winform
Trong các ví dụ trước mình cũng đã có hướng dẫn các bài viết về thêm xóa sửa, nhưng trong các bài đó mình sử dụng DataGridView.
Ở bài viết này, mình sẻ thực hiện trên Listview C# Winform
Video demo ứng dụng CRUD Listview Sqlserver Winform:
Ở bài demo này bao gồm các chức năng sau:
- Thêm dữ liệu
- Lưu dữ liệu
- Xóa dữ liệu
- Cập nhật chỉnh sửa
- Kiểm tra trùng mã sinh viên
- Tạo mã tự động
- Trigger chỉ cho phép nhập số vào trên ô textbox Học Bổng
Full source code c#:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Lession2
{
    public partial class FrmMain : Form
    {
        private readonly string CONNECTION_STRING = "Server=(local);Database=Lession2;Trusted_Connection=True;";
        private int _current_index_listview;
        public FrmMain()
        {
            InitializeComponent();          
            txt_ngaysinh.Format = DateTimePickerFormat.Custom;        
            txt_ngaysinh.CustomFormat = "dd 'tháng' MM 'năm' yyyy";
        }
        private void FrmMain_Load(object sender, EventArgs e)
        {
            LoadLopHoc();
            LoadData();
        }
        private void LoadData(int _currentIndex = 0)
        {
            var table_sinhvien = GetListStudent();
            DisplayDataToListView(table_sinhvien);
            if (table_sinhvien.Rows.Count > 0)
            {
               
                lst_danhsach.Items[_currentIndex].Selected = true;
                _current_index_listview = _currentIndex;
            }
            else
            {
                btn_xoa.Enabled = false;
                btn_sua.Enabled = false;
                txt_masv.Text = "";
                txt_tensv.Text = "";
                txt_hocbong.Text = "";
                txt_ngaysinh.Value = DateTime.Now;
            }
        }
        private void DisplayDataToListView(DataTable data)
        {
            lst_danhsach.Items.Clear();
            foreach (DataRow row in data.Rows)
            {
                ListViewItem item = new ListViewItem(row[0].ToString());
                for (int i = 1; i < data.Columns.Count; i++)
                {
                    item.SubItems.Add(row[i].ToString());
                }
                lst_danhsach.Items.Add(item);
            }
        }
        private DataTable GetListStudent()
        {           
            using (var conn = new SqlConnection(CONNECTION_STRING))
            {
                conn.Open();
                var commandText = @"SELECT sv.masv, sv.tensv, FORMAT(sv.ngaysinh,'dd/MM/yyyy') as ngaysinh_text,  gt.tengioitinh, sv.hocbong, lh.tenlop, sv.malop, sv.magioitinh, sv.ngaysinh	 FROM tbl_sinhvien sv
                                INNER JOIN tbl_gioitinh gt
                                ON sv.magioitinh = gt.magioitinh
                                INNER JOIN tbl_lophoc lh
                                ON sv.malop = lh.malop";
                using (var cmd = new SqlCommand(commandText, conn))
                {
                    var da = new SqlDataAdapter();
                    da.SelectCommand = cmd;
                    var ds = new DataSet();
                    da.Fill(ds);
                    return ds.Tables[0];
                }
            }
            
        }
        
        private void LoadLopHoc()
        {
           using(var conn = new SqlConnection(CONNECTION_STRING))
           {
                conn.Open();
                var commandText = "SELECT malop, tenlop FROM tbl_lophoc";
                using (var cmd = new SqlCommand(commandText, conn))
                {
                    var da = new SqlDataAdapter();
                    da.SelectCommand = cmd;
                    var ds = new DataSet();
                    da.Fill(ds);
                    cb_lophoc.DataSource = ds.Tables[0];
                    cb_lophoc.DisplayMember = "tenlop";
                    cb_lophoc.ValueMember = "malop";
                }
            }
        }
        private void btn_thoat_Click(object sender, EventArgs e)
        {
            var dlg = MessageBox.Show("Bạn có chắc chắn muốn đóng ứng dụng?", "Thông báo", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
            if(dlg == DialogResult.Yes)
            {
                Application.Exit();
            }
        }
        private void lst_danhsach_ItemSelectionChanged(object sender, ListViewItemSelectionChangedEventArgs e)
        {
            var sinhvien = e.Item;
            txt_masv.Text = sinhvien.SubItems[0].Text;
            txt_tensv.Text = sinhvien.SubItems[1].Text;
            txt_ngaysinh.Text = sinhvien.SubItems[2].Text;
            txt_hocbong.Text = sinhvien.SubItems[4].Text;
            if(sinhvien.SubItems[3].Text.Equals("Nam"))
            {
                rad_nam.Checked = true;
            }
            else
            {
                rad_nu.Checked = true;
            }
            cb_lophoc.SelectedValue = sinhvien.SubItems[6].Text;
            btn_them.Enabled = true;
            btn_luu.Enabled = false;
            btn_xoa.Enabled = true;
            btn_sua.Enabled = true;
            _current_index_listview = e.ItemIndex;
        }
        public string GetCodeStudentAuto()
        {
            using (var conn = new SqlConnection(CONNECTION_STRING))
            {
                conn.Open();
                var commandText = $@"SELECT CONCAT('SV', RIGHT(CONCAT('0000',ISNULL(right(max(masv),4),0) + 1),4))
                                            FROM dbo.tbl_sinhvien where masv like 'SV%'";
                using (var cmd = new SqlCommand(commandText, conn))
                {
                    return cmd.ExecuteScalar().ToString();
                }
            }
        }
        private void btn_them_Click(object sender, EventArgs e)
        {
            btn_luu.Enabled = true;
            btn_them.Enabled = false;
            btn_sua.Enabled = false;
            btn_xoa.Enabled = false;
            txt_masv.Text = "";
            txt_tensv.Text = "";
            txt_ngaysinh.Value = DateTime.Now;
            txt_hocbong.Text = "";
            txt_masv.Text = GetCodeStudentAuto();
            txt_tensv.Focus();
        }
        private void btn_luu_Click(object sender, EventArgs e)
        {
            var masv = txt_masv.Text;
            var tensv = txt_tensv.Text;
            var ngaysinh = txt_ngaysinh.Value;
            var hocbong = txt_hocbong.Text;
            var magioitinh = rad_nu.Checked == true ? 1 : 0;
            var malop = cb_lophoc.SelectedValue.ToString();
            if (string.IsNullOrEmpty(masv))
            {
                MessageBox.Show("Bạn chưa nhập mã sinh viên", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
                txt_masv.Focus();
                return;
            }
            if(masv.Length > 6)
            {
                MessageBox.Show("Bạn sinh viên chỉ tối đa 6 ký tự", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
                txt_masv.Focus();
                return;
            }
            //kiểm tra trùng mã
            var isExists = CheckCodeIsExisted(masv);
            if (isExists)
            {
                MessageBox.Show($"Mã sinh viên {masv} đã tồn tại.", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
                txt_masv.Focus();
                return;
            }
            if (string.IsNullOrEmpty(tensv))
            {
                MessageBox.Show($"Bạn chưa nhập tên sinh viên", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
                txt_tensv.Focus();
                return;
            }
            using (var conn = new SqlConnection(CONNECTION_STRING))
            {
                conn.Open();
                var commandText = $"INSERT INTO tbl_sinhvien(masv, tensv, ngaysinh, malop, magioitinh, hocbong) VALUES(@masv, @tensv, @ngaysinh, @malop, @magioitinh, @hocbong)";
                using (var cmd = new SqlCommand(commandText, conn))
                {
                    cmd.Parameters.AddWithValue("@masv", masv);
                    cmd.Parameters.AddWithValue("@tensv", tensv);
                    cmd.Parameters.AddWithValue("@ngaysinh", ngaysinh);
                    cmd.Parameters.AddWithValue("@hocbong", hocbong);
                    cmd.Parameters.AddWithValue("@magioitinh", magioitinh);
                    cmd.Parameters.AddWithValue("@malop", malop);
                    var affectedRow = cmd.ExecuteNonQuery();
                    if (affectedRow > 0)
                    {
                        LoadData();
                        btn_them.Enabled = true;
                        btn_luu.Enabled = false;
                        btn_sua.Enabled = true;
                        btn_xoa.Enabled = true;
                        //MessageBox.Show($"Đã thêm sinh viên {tensv} thành công.", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        
                    }
                    else
                    {
                        MessageBox.Show($"Thêm dữ liệu thất bại.", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }
        }
        private bool CheckCodeIsExisted(string masv)
        {
            using (var conn = new SqlConnection(CONNECTION_STRING))
            {
                conn.Open();
                var commandText = $"SELECT count(*) FROM tbl_sinhvien WHERE masv='{masv}'";
                using (var cmd = new SqlCommand(commandText, conn))
                {                   
                    return Convert.ToInt32(cmd.ExecuteScalar()) > 0;
                }
            }
        }
        private void txt_hocbong_KeyPress(object sender, KeyPressEventArgs e)
        {
            e.Handled = e.KeyChar != (char)Keys.Back  && !char.IsDigit(e.KeyChar);
        }
        private void btn_xoa_Click(object sender, EventArgs e)
        {
            var masv = txt_masv.Text;
            if (!string.IsNullOrEmpty(masv))
            {
                var dlg = MessageBox.Show($"Bạn có chắn chắn muốn xóa sinh viên {txt_tensv.Text} ?", "Thông báo", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                if(dlg == DialogResult.Yes)
                {
                    using (var conn = new SqlConnection(CONNECTION_STRING))
                    {
                        conn.Open();
                        var commandText = $"DELETE From tbl_sinhvien where masv='{masv}'";
                        using (var cmd = new SqlCommand(commandText, conn))
                        {
                            var affectedRow = cmd.ExecuteNonQuery();
                            if (affectedRow > 0)
                            {
                                LoadData();                             
                            }
                            else
                            {
                                MessageBox.Show($"Xóa dữ liệu thất bại.", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            }
                        }
                    }
                }
            }
        }
        private void btn_sua_Click(object sender, EventArgs e)
        {
            var masv = txt_masv.Text;
            var tensv = txt_tensv.Text;
            var ngaysinh = txt_ngaysinh.Value;
            var hocbong = txt_hocbong.Text;
            var magioitinh = rad_nu.Checked == true ? 1 : 0;
            var malop = cb_lophoc.SelectedValue.ToString();
            if (string.IsNullOrEmpty(masv))
            {
                MessageBox.Show("Bạn chưa nhập mã sinh viên", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
                txt_masv.Focus();
                return;
            }
            if (masv.Length > 6)
            {
                MessageBox.Show("Bạn sinh viên chỉ tối đa 6 ký tự", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
                txt_masv.Focus();
                return;
            }
            //kiểm tra trùng mã
            var isExists = CheckCodeIsExisted(masv);
            if (!isExists)
            {
                MessageBox.Show($"Mã sinh viên {masv} không tồn tại.", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
                txt_masv.Focus();
                return;
            }
            if (string.IsNullOrEmpty(tensv))
            {
                MessageBox.Show($"Bạn chưa nhập tên sinh viên", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
                txt_tensv.Focus();
                return;
            }
            using (var conn = new SqlConnection(CONNECTION_STRING))
            {
                conn.Open();
                var commandText = $"UPDATE tbl_sinhvien SET tensv=@tensv, ngaysinh=@ngaysinh, malop=@malop, magioitinh=@magioitinh, hocbong =@hocbong WHERE masv=@masv";
                using (var cmd = new SqlCommand(commandText, conn))
                {
                    cmd.Parameters.AddWithValue("@masv", masv);
                    cmd.Parameters.AddWithValue("@tensv", tensv);
                    cmd.Parameters.AddWithValue("@ngaysinh", ngaysinh);
                    cmd.Parameters.AddWithValue("@hocbong", hocbong);
                    cmd.Parameters.AddWithValue("@magioitinh", magioitinh);
                    cmd.Parameters.AddWithValue("@malop", malop);
                    var affectedRow = cmd.ExecuteNonQuery();
                    if (affectedRow > 0)
                    {                       
                        LoadData(_current_index_listview);                      
                    }
                    else
                    {
                        MessageBox.Show($"Chỉnh sửa dữ liệu thất bại.", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }
        }
    }
}
Thanks for watching!
Pass unrar: laptrinhvb.net

![[C#] Hướng dẫn thêm, xóa, sửa listview sqlserver](https://laptrinhvb.net/uploads/users/9a8cb514e4428e85fb4ca07588e9103f.png)

![[C#] LINQ trong CSharp - Phần một](https://laptrinhvb.net/uploads/source/image_baiviet/833b1af041117b932108bd2ed9e3fc96.jpg)
![[C#] Chia sẻ source code tạo hiệu ứng pixel Image trên winform](https://laptrinhvb.net/uploads/source/new_image_baiviet/effect_pixel_image_thumb.png)
![[C#] 14 tỷ, 6 tháng lãi suất bao nhiêu tiền lãi? Hướng dẫn viết tool tính lãi xuất ngân hàng](https://laptrinhvb.net/uploads/source/vbnet/tinhlaisuat_nganhang.jpg)
![[C#] Hướng dẫn lấy danh sách múi giờ Timezone UTC trên thế giới trên Winform](https://laptrinhvb.net/uploads/source/new_image_baiviet/time_zone_utc.png)
![[C#] Hướng dẫn show Tooltip tại vị trí control đang active trên winform](https://laptrinhvb.net/uploads/source/vbnet/show_tooltip.gif)
![[C#] Chia sẽ Class Download file chia thành nhiều phần nhỏ để tải](https://laptrinhvb.net/uploads/source/csharp/split_download_thumb.jpg)
![[C#] Tạo tài khoản đăng nhập Windows NT trong lập trình csharp](https://laptrinhvb.net/uploads/source/image_baiviet/8d2d015db436666ed0d6f8893b4b271a.jpg)

![[C#] Tách hình các hình Frame JPG từ file hình GIF](https://laptrinhvb.net/uploads/source/csharp/frame_image_csharp.png)
![[C#] Chuyển đổi nhiều file hình ảnh thành một file PDF - sử dụng  PdfSharp library](https://laptrinhvb.net/uploads/source/csharp/convert_image_to_pdf_thumb.jpg)
![[C#] Chia sẽ hàm bỏ dấu tiếng việt trong lập trình Csharp](https://laptrinhvb.net/uploads/source/image_baiviet/3b7f5fe03e368394ff8bd6a95d94ecbf.jpg)
![[C#] Chia sẻ source code tool kiểm tra domain website](https://laptrinhvb.net/uploads/source/new_image_baiviet/PING_DOMAIN_THUMB.png)

![[C#] Làm việc với NULL sử dụng toán tử ?? và ? trong lập trình winform](https://laptrinhvb.net/uploads/source/csharp/null_csharp_thumb.png)
![[C#] Tách file thành nhiều phần để download](https://laptrinhvb.net/uploads/source/image_baiviet/de1a2476a93e212f093115ec3940926d.png)
![[C#] Hướng dẫn xuất dữ liệu từ data ra file Excel template sử dụng Epplus](https://laptrinhvb.net/uploads/source/web/export_excel_template_epplus_csharp.png)
![[C#] Viết ứng dụng get dữ liệu google suggest trong lap trinh csharp](https://laptrinhvb.net/uploads/source/image_baiviet/2ef41a883961b74f7e735053f1d41dad.png)
![[C#] Hướng dẫn đọc tất cả email qua giao thức IMAP Gmail](https://laptrinhvb.net/uploads/source/new_image_baiviet/gmail_thumb.jpg)

![[C#] Hướng dẫn sử dụng Font Awesome làm icon trong Winform](https://laptrinhvb.net/uploads/source/csharp/font_awesome_thumb.jpg)
![[C#] Hướng dẫn import excel big data vào database sqlserver](https://laptrinhvb.net/uploads/source/csharp/IMPORTEXCELBIG_DATA_THUMB.jpg)
![[C#] Hướng dẫn viết ứng dụng đơn giản shutdown, restart, sleep, lock, logoff, hibernation trong windows](https://laptrinhvb.net/uploads/source/image_baiviet/3a189ee8ae4f2252a4aa9d70c549e407.jpg)
![[C#] Hướng dẫn viết tools tự động upload video lên Youtube  - using Api v3 Csharp](https://laptrinhvb.net/uploads/source/image_baiviet/166b02ef5dab9e7402d9068374ca40d0.png)
![[C#] Import dữ liệu file Excel (xls, xlsx, csv) vào Dataset hoặc Datatable](https://laptrinhvb.net/uploads/source/image_baiviet/95dae3f410d40a147787f979ba5cc059.png)
![[C#] Hướng dẫn lập trình mô hình ba lớp three layer trong csharp](https://laptrinhvb.net/uploads/source/csharp/three_tiger.jpg)
