NEWS

[DEVEXPRESS] Thêm xóa sửa sqlserver csharp sử dụng VBSqlHelper

[DEVEXPRESS] Thêm xóa sửa sqlserver csharp sử dụng VBSqlHelper
Đăng bởi: Thảo Meo - Lượt xem: 5588 13:02:02, 22/07/2021DEVEXPRESS   In bài viết

Xin chào các bạn, bài viết hôm nay mình sẽ tiếp tục hướng dẫn các bạn cách thêm xóa sửa dữ liệu trên C#, Winform Devexpress.

[DEVEXPRESS] CRUD Database sqlserver c#

Bài viết hướng dẫn các bạn, cơ bản cách thêm xóa sửa làm việc với sqlserver.

CRUD_THUMB

Bài viết chỉ demo cách các bạn làm việc với cơ sở dữ liệu sqlserver một cách đơn giản.

Các bạn có thể xem video bên dưới để thực hiện từng bước:

Source code C#:

Class cấu hình thông tin kết nối database ở class program.cs:

using DevExpress.LookAndFeel;
using DevExpress.Skins;
using DevExpress.UserSkins;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;

namespace CRUD_STUDENT_DEMO
{
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            VBSQLHelper.SQLHelper.SERVER_NAME = ".";
            VBSQLHelper.SQLHelper.DATABASE = "CRUD_STUDENT";
            VBSQLHelper.SQLHelper.USERNAME_DB = "sa";
            VBSQLHelper.SQLHelper.PASSWORD_DB = "minh123";
            VBSQLHelper.SQLHelper.ConnectString(); // nhớ hàm này nhé.
            Application.Run(new Form1());
        }
    }
}

Tiếp đến, chúng ta sẽ tạo 1 class Student.cs

using Dapper.Contrib.Extensions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CRUD_STUDENT_DEMO
{
    [Table("tbl_student")]
    public class Student
    {
        [Key]
        public int id { get; set; }
        public string firstname { get; set; }
        public string lastname { get; set; }
        public string address { get; set; }
        public int age { get; set; }
        public bool gender { get; set; }
    }
}

Và cuối cùng là source code chạy trên FrmMain.cs

using DevExpress.XtraEditors;
using DevExpress.XtraGrid.Views.Grid;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using VBSQLHelper;

namespace CRUD_STUDENT_DEMO
{
    public partial class Form1 : DevExpress.XtraEditors.XtraForm
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            var data_gender = SQLHelper.ExecQueryDataAsDataTable("select * from tbl_gender");
            cb_gender.Properties.DataSource = data_gender;
            cb_gender.Properties.ValueMember = "id";
            cb_gender.Properties.DisplayMember = "name";

            LoadDataToGridview();
        }

        private void btn_save_Click(object sender, EventArgs e)
        {
            var id = txt_id.Text;
            var firstname = txt_firstname.Text;
            var lastname = txt_lastname.Text;
            var address = txt_address.Text;
            var age = Convert.ToInt32(spin_age.EditValue);
            var gender = Convert.ToBoolean(cb_gender.EditValue);

            if (string.IsNullOrEmpty(id))
            {
                XtraMessageBox.Show("Enter your id", "Information");
                txt_id.Focus();
                return;
            }

            //check id is existe

            var isExist = Convert.ToInt32(SQLHelper.ExecQuerySacalar($"select count(*) from tbl_student where id='{id}'")) > 0;
            if (isExist)
            {
                XtraMessageBox.Show($"Your id {id} is existed!", "Information");
                txt_id.Focus();
                txt_id.SelectAll();
                return;
            }

            if (string.IsNullOrEmpty(firstname))
            {
                XtraMessageBox.Show("Enter your FirstName", "Information");
                txt_firstname.Focus();
                return;
            }
            if (string.IsNullOrEmpty(lastname))
            {
                XtraMessageBox.Show("Enter your LastName", "Information");
                txt_lastname.Focus();
                return;
            }
            if (string.IsNullOrEmpty(address))
            {
                XtraMessageBox.Show("Enter your Address", "Information");
                txt_address.Focus();
                return;
            }

            if (age<1)
            {
                XtraMessageBox.Show("Enter your Age", "Information");
                spin_age.Focus();
                return;
            }

            if(cb_gender.EditValue == null)
            {
                cb_gender.ShowPopup();
                return;
            }
            var student = new Student
            {
                id = Convert.ToInt32(id),
                firstname = firstname,
                lastname = lastname,
                address = address,
                age = age,
                gender = gender
            };
            var affectrow = SQLHelper.Insert(student);
            if (affectrow > 0)
            {
                txt_id.Text = "";
                txt_firstname.Text = "";
                txt_lastname.Text = "";
                txt_address.Text = "";
                spin_age.EditValue = 0;
                cb_gender.EditValue = null;
                LoadDataToGridview();
            }
            else
            {
                XtraMessageBox.Show("Insert Student Fail", "Information",MessageBoxButtons.OK, MessageBoxIcon.Error);
            }


        }

        public void LoadDataToGridview()
        {
            var dataStudents = SQLHelper.ExecQueryData<Student>("select * from tbl_student");
            gridControl1.DataSource = dataStudents;
        }

        private void btnEdit_Click(object sender, EventArgs e)
        {
            var id = txt_id.Text;
            var firstname = txt_firstname.Text;
            var lastname = txt_lastname.Text;
            var address = txt_address.Text;
            var age = Convert.ToInt32(spin_age.EditValue);
            var gender = Convert.ToBoolean(cb_gender.EditValue);
            var studentEdit = new Student
            {
                id = Convert.ToInt32(id),
                firstname = firstname,
                lastname = lastname,
                address = address,
                age = age,
                gender = gender
            };

            SQLHelper.Update(studentEdit);
            LoadDataToGridview();

        }

        private void gridView1_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            var gridview = sender as GridView;
            if (gridview.IsDataRow(e.FocusedRowHandle))
            {
                var student = gridview.GetFocusedRow() as Student;
                txt_id.EditValue = student.id;
                txt_firstname.EditValue = student.firstname;
                txt_lastname.EditValue = student.lastname;
                txt_address.EditValue = student.address;
                spin_age.EditValue = student.age;
                cb_gender.EditValue = student.gender;
            }
        }

        private void gridView1_RowCellClick(object sender, RowCellClickEventArgs e)
        {
            if(e.Column == colDelete)
            {
                var studentDelete = gridView1.GetFocusedRow() as Student;
                var dlg = XtraMessageBox.Show($"Are you sure Delete Student {studentDelete.firstname} {studentDelete.lastname}?", "Infomation", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
                if(dlg == DialogResult.Yes)
                {
                    SQLHelper.Delete(studentDelete);
                    gridView1.DeleteSelectedRows();
                }
            }
        }
    }
}

Thanks for watching!

DOWNLOAD SOURCE

THÔNG TIN TÁC GIẢ

BÀI VIẾT LIÊN QUAN

[DEVEXPRESS] Thêm xóa sửa sqlserver csharp sử dụng VBSqlHelper
Đăng bởi: Thảo Meo - Lượt xem: 5588 13:02:02, 22/07/2021DEVEXPRESS   In bài viết

CÁC BÀI CÙNG CHỦ ĐỀ

Đọc tiếp
.