2017년 2월 13일 월요일

[C#/닷넷/xamarin/WPF교육/C#네트워크교육학원추천_탑크리에듀](닷넷,C#,WPF 예제)데이터 바인딩을 이용하여 오라클 EMP 테이블 데이터를

(닷넷,C#,WPF 예제)데이터 바인딩을 이용하여 오라클 EMP 테이블 데이터를 ListView에 뿌리기(ODP.NET, ItemTemplate, Data Binding)_닷넷/C#/자마린/WPF 추천학원
n  ODP.NET을 이용하여 오라클 DB의 EMP 테이블의 내용을 ListView에 출력하는 예제를 작성해 보자.
n  Visual Studio 2015에서 ODP.NET을 사용하기 위해서는 Oracle Developer Tool for Visual Studio 2015를 다운받아 설치하면 된다.(http://www.oracle.com/technetwork/topics/dotnet/downloads/odacmsidownload-2745497.html)
n  오라클홈 디렉토리 아래 NETWORK\Admin 폴더에 tnsnames.ora 파일에 다음 접속하고자 하는 Oracle Server의 접속정보 추가
ONJ =
  (DESCRIPTION =
    (ADDRESS = (PROTOCOL = TCP)(HOST = localhost)(PORT = 1521))
    (CONNECT_DATA =
      (SERVER = DEDICATED)
      (SERVICE_NAME = onj)  ß DB
    )
  )
n  WPF 응용프로그램 형태의 프로젝트를 생성(프로젝트명 : WpfOracleTest)
n  참조 추가 프로젝트 생성 후 솔루션 탐색기 -> 참조 -> 참조추가 선택 후 찾아보기” 버튼을 클릭하여 %ORACLE_HOME%\ODP.NET\bin\2.x\Oracle.DataAccess.dll을 선택하여 추가하자.
n  테스트 PC가 64Bit 윈도우10 이므로 프로젝트에서 마우스 오른쪽 속성 선택 후 빌드 -> 플랫폼 대상(Target Platform)을 x64로 선택한다. (32Bit인 경우 생략)
n  EmpViewModel.cs
using System;
using System.ComponentModel;
using System.Windows.Input;


namespace WpfOracleTest
{
    public class EmpViewModel 
    {       
        int empno = 0;
        string ename = string.Empty;
        string job = string.Empty;


 
        // public 프로퍼티
        public int Empno
        {
            get { return empno; }
            set { this.empno = value;  }
        }

        // public 프로퍼티
        public string Ename
        {
            get { return ename; }
            set { this.ename = value; }
        }


        // public 프로퍼티
        public string Job
        {
            get { return job; }
            set { this.job = value; }
        }

        
    }

}

n  MainWindow.xaml
<Window x:Class="WpfOracleTest.MainWindow"
        xmlns:local="clr-namespace:WpfOracleTest"
        mc:Ignorable="d"
        Title="MainWindow" Height="350" Width="461.659">
    <Grid Margin="0,0,3.2,-0.2">
        <Button x:Name="button" Content="DB Connect" HorizontalAlignment="Left" Margin="43,28,0,0" VerticalAlignment="Top" Width="75" RenderTransformOrigin="0.391,-0.29"Click="DB_Connect"/>
        <ListView Margin="10,66,10,10" Name="lstView">
            <ListView.ItemTemplate>
                <DataTemplate>
                    <WrapPanel>
                        <TextBlock Text="Empno: " />
                        <TextBlock Text="{Binding Empno}" FontWeight="Bold" />
                        <TextBlock Text=", " />
                        <TextBlock Text=" (" />
                        <TextBlock Text="Ename: " />
                        <TextBlock Text="{Binding Ename}" TextDecorations="Underline" FontWeight="Bold" />
                        <TextBlock Text=")" />
                        <TextBlock Text="{Binding Job}"  Foreground="Blue" Cursor="Hand" />
                    </WrapPanel>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>
        <Button x:Name="button1" Content="Get Data" HorizontalAlignment="Left"Margin="137,28,0,0" VerticalAlignment="Top" Width="75" Click="Select_Emp"/>
    </Grid>
</Window>

n  MainWindow.xaml
using System;
using System.Collections.Generic;
using System.Windows;
using System.Data;
using Oracle.DataAccess.Client;


namespace WpfOracleTest
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        OracleConnection conn;

        private void DB_Connect(object sender, RoutedEventArgs e)
        {
            try
            {
                string strCon = "data source=onj;User ID=scott;Password=tiger";
                conn = new OracleConnection(strCon);
                conn.Open();

                MessageBox.Show("DB Connection OK!");

            }
            catch(Exception error)
            {
                MessageBox.Show(error.ToString());
            }           
        }

        private void Select_Emp(object sender, RoutedEventArgs e)
        {
            string sql = "select empno, ename, job from emp ";

            OracleCommand comm = new OracleCommand();
            if(conn == null) DB_Connect(thisnull);
            comm.Connection = conn;
            comm.CommandText = sql;
                       
            OracleDataReader reader = comm.ExecuteReader(CommandBehavior.CloseConnection);
            List<EmpViewModel> emps = new List<EmpViewModel>();
            while (reader.Read())
            {
                emps.Add(new EmpViewModel() { Empno = reader.GetInt32(reader.GetOrdinal("empno")),
                                              Ename = reader.GetString(reader.GetOrdinal("ename")),
                                              Job = reader.GetString(reader.GetOrdinal("job"))
                });
            }

            lstView.ItemsSource = emps;
        }
    }
}

n  실행화면
066117be0ad9045c67d53e9da88866cf_1482367
 



댓글 없음:

댓글 쓰기