디비 연동

sz L·2023년 4월 24일
0

WPF

목록 보기
6/9
post-thumbnail

SqlServer(SSMS)




visual studio



App.xaml

<Application x:Class="wp10_employeesApp.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:local="clr-namespace:wp10_employeesApp">
    <Application.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary>
                    <local:Bootstrapper x:Key="Bootstrapper"/>
                </ResourceDictionary>

                <ResourceDictionary>
                    <ResourceDictionary.MergedDictionaries>
                        <!-- MahApps.Metro resource dictionaries. Make sure that all file names are Case Sensitive! -->
                        <ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Controls.xaml" />
                        <ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Fonts.xaml" />
                        <!-- Theme setting -->
                        <ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Themes/Light.Blue.xaml" />
                    </ResourceDictionary.MergedDictionaries>
                </ResourceDictionary>
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>

    </Application.Resources>
</Application>

Bootstrapper.cs

using Caliburn.Micro;   // BootstrapperBase 사용하기위함
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
//using wp09_caliburnApp.ViewModels;      // MainViewModel클래스 쓰기 위함
using wp10_employeesApp.ViewModels;

namespace wp10_employeesApp
{
    // Caliburn 으로 MVVM 실행할 때 주요설정 진행
    public class Bootstrapper : BootstrapperBase
    {
        public Bootstrapper()
        {
            Initialize(); // Caliburn MVVM 초기화
        }

        // 시작한 후에 초기화 진행
        protected async override void OnStartup(object sender, StartupEventArgs e)
        {
            //base.OnStartup(sender, e);  // 부모 클래스 실행은 주석처리
            await DisplayRootViewForAsync<MainViewModel>();
        }
    }
}

Views

MainView.xaml

<mah:MetroWindow 
    x:Class="wp10_employeesApp.Views.MainView"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:iconPacks="http://metro.mahapps.com/winfx/xaml/iconpacks"
    xmlns:mah="http://metro.mahapps.com/winfx/xaml/controls"
    xmlns:local="clr-namespace:wp10_employeesApp.Views"
    mc:Ignorable="d"
    Title="Employees App" Height="450" Width="800" WindowStartupLocation="CenterScreen">
    <Grid>
        <DataGrid ItemsSource="{Binding ListEmployee}"/>


    </Grid>
</mah:MetroWindow>

MainView.xaml.cs

using MahApps.Metro.Controls;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace wp10_employeesApp.Views
{
    /// <summary>
    /// MainWindow.xaml에 대한 상호 작용 논리
    /// </summary>
    public partial class MainView : MetroWindow
    {
        public MainView()
        {
            InitializeComponent();
        }
    }
}

ViewModels

MainViewModel.cs

using Caliburn.Micro;
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using wp10_employeesApp.Models;

namespace wp10_employeesApp.ViewModels
{
    public class MainViewModel : Screen
    {
        private Employees employee;

        public BindableCollection<Employees> ListEmployee { get; set; }    

        public int Idx
        {
            get => employee.Idx;
            set
            {
                employee.Idx = value;
                NotifyOfPropertyChange(nameof(Idx));
            }
        }
        public string FullName
        {
            get => employee.FullName;
            set
            {
                employee.FullName = value;
                NotifyOfPropertyChange(nameof(FullName));
            }
        }
        public int Salary
        {
            get => employee.Salary;
            set
            {
                employee.Salary = value;
                NotifyOfPropertyChange(nameof(Salary)); 
            }
        }
        public string DeptName
        {
            get => employee.DeptName; 
            set
            {
                employee.DeptName = value;
                NotifyOfPropertyChange(nameof(DeptName));
            }
        }
        public string Address
        {
            get => employee.Address; 
            set
            {
                employee.Address = value;
                NotifyOfPropertyChange(nameof(Address));
            }
        }
        public MainViewModel()
        {
            using (SqlConnection conn = new SqlConnection("Data Source=localhost;Initial Catalog=pknu;User ID=sa;Password=12345"))
            {
                conn.Open();

                string sqlQuery = @"SELECT [Idx]
                                          ,[FullName]
                                          ,[Salary]
                                          ,[DeptName]
                                          ,[Address]
                                      FROM [dbo].[Employees]";
                SqlCommand selCommand = new SqlCommand(sqlQuery, conn);
                SqlDataReader reader = selCommand.ExecuteReader();
                ListEmployee = new BindableCollection<Employees>();

                while (reader.Read())
                {
                    var emp = new Employees
                    {
                        Idx = int.Parse(reader["Idx"].ToString()),
                        FullName = reader["FullName"].ToString(),
                        Salary = int.Parse(reader["Salary"].ToString()),
                        DeptName = reader["DeptName"].ToString(),
                        Address = reader["Address"].ToString()
                    };
                    ListEmployee.Add(emp);
                }
            }
        }
    }
}

Models

Employees.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace wp10_employeesApp.Models
{
    public class Employees
    {
        private int salary;

        public int Idx { get; set; }
        public string FullName { get; set; }
        public int Salary 
        {
            get => salary;
            set
            {
                if(value <=0 || value >50000000)
                {
                    throw new Exception("급여 ERROR!!");
                }
                else
                {
                    salary = value;
                }
            }
        } 
        public string DeptName { get; set; }
        public string Address { get; set; } 
    }
}

실행결과

profile
가랑비는 맞는다 하지만 폭풍은 내 것이야

0개의 댓글