레이블이 c#인 게시물을 표시합니다. 모든 게시물 표시
레이블이 c#인 게시물을 표시합니다. 모든 게시물 표시

2013년 11월 25일 월요일

C# 학습




  • 배열

  • 배열


    할당된 배열의 사이즈 변경


    String [] arr = new String[10];

    for(int i=0; i < 20; i++){
    if(i == arr.Length) {
    Array.Resize<String>(ref arr, arr.Length + 1);
    arr[arr.Length - 1] = "값";
    else {
    arr[i] = "값2";
    }



    [출처] [C#] 동적배열|작성자 monk773

    2013년 7월 21일 일요일

    c# oledb dbf

    string filepath = @"c:\aaa;
    string connstring =
    "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filepath + ";Extended Properties=dBASE IV;"
    OleDbConnection conn = new OleDbConnection(connstring);

    conn.Open();

    using (OleDbCommand cmd = new OleDbCommand("SELECT * FROM PART.DBF", conn))
                {
                    OleDbDataAdapter adpt = new OleDbDataAdapter(cmd);
                    DataTable dt = new DataTable();
                 
                    adpt.Fill(dt);
                    dataGridView1.DataSource = dt;
                }

    dbf는 파일이 태이블이다.

    2012년 6월 23일 토요일

    로그인폼


            private void loginbutton_Click(object sender, EventArgs e)
            {
                if (checkData() == true)
                {
                    this.label1.Text = "로그인 성공";
                }
            }

            private bool checkData()
            {
                if (this.idtextBox.Text == "")
                {
                    MessageBox.Show("로그인 아이디를 입력하세요", "알림", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    this.idtextBox.Focus();
                    return false;
                }
                else if (this.passtextBox.Text == "")
                {
                    MessageBox.Show("로그인 비밀번호를 입력해주세요", "알림", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    this.passtextBox.Focus();
                    return false;
                }
                else
                {
                    if (this.idtextBox.Text == "test")
                    {
                        if (this.passtextBox.Text == "12345")
                        {
                            return true;
                        }
                        else
                        {
                            this.label1.Text = "일치하는 비밀번호가 없습니다.";
                            this.passtextBox.Focus();
                            return false;
                        }
                    }
                    else
                    {
                        this.label1.Text = "일치한는 아이디가 없습니다.";
                        this.idtextBox.Focus();
                        return false;
                    }
                }
            }

           

            private void passtextBox_KeyDown(object sender, KeyEventArgs e)
            {
                if (e.KeyCode == Keys.Enter)
                {
                    if (checkData() == true)
                    {
                        this.label1.Text = "로그인성공";
                    }
                }
            }

            private void closebutton_Click(object sender, EventArgs e)
            {
                this.Close();
            }
         

         
        }

    2012년 6월 21일 목요일

    기본문법(타입)


    값 타입


    스택에할당

    -구조체

    struct 이름
    {
    맴버 선언문
    }

    맴버선언문에는 필드와 메소드 생성자등을 선언 할수있다..
    필드는 한정자를 따로 정하지 않으면 private이다.

    구조체는 변수 선언후 바로 변수를 쓸수있다(클래스는 인스턴스 생성후 사용 가능)

    구조체타입 구조체 변수 = new 구조체타입();
    new는 생성자를 쓰기위함다.(인스턴스는 만들어지지않고 힙에 할당 돼지 않는다.)



    참조타입

    힙에 할당
    사용이 끝나면 가비지컬렉터에 의해 메모리가 관리된다.


    -배열


    타입[] 변수명;

    배열은 참조형이므로 변수 자체가 실제 데이터를 저장하지 않는다.(변수는 null값을 가진다.)
    new 연산자에 의해 힙에 데이터 저장을 위한 별도의 공간이 할당되고 배열
    변수는 이 위치만을 가진다.



    타입[] 변수명 = new 타입[];

    int[] arr = new int[5] {1, 2, 3, 4, 5};

    arr은 정수형 배열이며 5개의 공간을 할당 받으며 각각의 공간이 {}안의 값들로 초기화 된다.
    초기값이 있을시에 []안의 배열의 길이를 표기할 필요가 없다.
    컴파일러가 요소의 수를 세어 메모리 크기를 할당하기 때문에 초기값이 있을시엔
    배열의 크기를 표기 않는것이 좋다.

    int[] arr = {1, 2, 3, 4, 5};

    new int[] 마저 생략되었는데 이유는
    초기값이 있으므로 메모리를 할당할것으로 인식하는 똑똑한 컴파일러를 가지고 있기 때문

    배열의 초기값은 메모리를 할당받은후에는 할수 없다.
    즉 다음은 컴파일 되지 않는다.

    int[] arr = new int[5]; //초기화 하지 않으면 길이를지정 해야하는듯..(확인않함)
    arr = {1, 2, 3, 4, 5};



    2012년 6월 19일 화요일

    list


        class Program
        {
            static void Main(string[] args)
            {
                List<test> testList = new List<test>();
                testList.Add(new test() { name = "a", num = 100 });
                testList.Add(new test() { name = "b", num = 200 });

                foreach (test a in testList)
                {
                    Console.WriteLine("name ={0},\n num = {1}", a.name, a.num);
                }
               
            }
        }

        public class test
        {
            public string name;
            public int num;
        }
    }

    list에 객체를 담아본다.

    2012년 6월 15일 금요일

    수학함수

    using System;




    class MathTest1
    {
    static void Main(string[] args)
    {
    // 절대값


    // 절대값이란, 수직선상에서 0으로부터의 거리입니다. 스칼라양이죠.
    // 참고로 스칼라란 크기만 있는 값이고, 벡터는 크기와 방향이 있는 값입니다.
    // 따라서, 절대값을 풀면 항상 양의 값만 나옵니다.




    double d1 = -1.23;
    double d2 = Math.Abs(d1);
    Console.WriteLine("Math.Abs {0} => {1}", d1, d2); // Math.Abs -1.23 => 1.23




    // 올림
    d1 = 1.23;
    d2 = Math.Ceiling(d1);
    Console.WriteLine("Math.Ceiling {0} => {1}", d1, d2); // Math.Ceiling 1.23 => 2


    d1 = -1.23;
    d2 = Math.Ceiling(d1);
    Console.WriteLine("Math.Ceiling {0} => {1}", d1, d2); // Math.Ceiling -1.23 => -1




    // 내림
    d1 = 1.23;
    d2 = Math.Floor(d1);
    Console.WriteLine("Math.Floor {0} => {1}", d1, d2); // Math.Floor 1.23 => 1


    d1 = -1.23;
    d2 = Math.Floor(d1);
    Console.WriteLine("Math.Floor {0} => {1}", d1, d2); // Math.Floor -1.23 => -2




    // 반올림
    d1 = 1.23;
    d2 = Math.Round(d1);
    Console.WriteLine("Math.Floor {0} => {1}", d1, d2); // Math.Round 1.23 => 1


    d1 = -1.23;
    d2 = Math.Round(d1);
    Console.WriteLine("Math.Floor {0} => {1}", d1, d2); // Math.Round -1.23 => -1




    // 최대값
    d1 = 1;
    d2 = 2;
    Console.WriteLine("Math.Max {0} , {1} Max {2}", d1, d2, Math.Max(d1, d2)); // Math.Max 1 , 2 Max 2




    // 최소값
    d1 = 1;
    d2 = 2;
    Console.WriteLine("Math.Min {0} , {1} Min {2}", d1, d2, Math.Min(d1, d2)); // Math.Min 1 , 2 Min 1




    // power
    d1 = 10;
    d2 = Math.Pow(d1, 2);
    Console.WriteLine("Math.Pow {0} => {1}", d1, d2); // Math.Pow 10 => 100




    // 계산테스트
    double a = 16666.67;
    double b = 3333.33;
    double c = a - b;
    Console.WriteLine("{0}", c); // 결과 : 13333.34




    // 표시는 13333.34 로 되지만 실제로 13333.34 값과 비교해 보면 "다르다" 라고 나온다.
    if (c == 13333.34)
    {
    Console.WriteLine("같다");
    }
    else
    {
    Console.WriteLine("다르다"); // "다르다"
    }




    double d = 13333.339999999998;
    Console.WriteLine("{0}", d); // 결과 : 13333.34




    if (c == d)
    {
    Console.WriteLine("같다"); // "같다"
    }
    else
    {
    Console.WriteLine("다르다");
    }




    d = 13333.33999999999;
    Console.WriteLine("{0}", d); // 결과 : 13333.34




    if (c == d)
    {
    Console.WriteLine("같다");
    }
    else
    {
    Console.WriteLine("다르다"); // "다르다"
    }




    d = 13333.3399999999;
    Console.WriteLine("{0}", d); // 결과 : 13333.3399999999


    }
    }
    [출처] C# 수학함수|작성자 빨간토끼

    2012년 5월 2일 수요일

    application 갱신하기


    Aplication.DoEvents();

    2012년 5월 1일 화요일

    지연하기

    System.Threading.Thread.Sleep(3);


    2012년 4월 25일 수요일

    조건문(switch)




    namespace ConsoleApplication1
    {
        class Program
        {
            static void Main(string[] args)
            {
                string caseValue;

                Console.Write("입력 :");
                caseValue = Console.ReadLine();

                switch (caseValue)//정수,문자열,bool,char,enum등이 될수있다.
                {
                    case "aa":
                        Console.WriteLine("case1문장");
                        break;

                    case "bb":
                        Console.WriteLine("case2문장");
                        break;
                    case "cc":
                        Console.WriteLine("case3문장");
                        break;
                    default://위의 case의 값과 일치하지 않을경우 default실행
                        Console.WriteLine("나머지...");
                        break;

                }
            }
        }
    }

    2012년 4월 24일 화요일

    델리게이트




    001: using System;
    002: //델리게이트 선언
    003: delegate void dele1();
    004: delegate int dele2(int a,int b);
    005: class MainClass
    006: {
    007:    static void Main(string[] args)
    008:    {
    009:           //Math클래스 선언및 인스턴스화
    010:           MathClass MathClass=new MathClass();
    011:           //델리게이트 선언및 인스턴스화
    012:           dele1 Sum1=new dele1(MathClass.Intro);
    013:           dele2 Sum2=new dele2(MathClass.Sum);
    014:           //델리게이트에 위임된 메서드 실행
    015:           Sum1();
    016:           Console.WriteLine("Result : {0}",Sum2(-10,90));
    017:    }
    018: }
    019: class MathClass
    020: {
    021:    public void Intro()
    022:    {
    023:           Console.WriteLine("계산을 시작합니다.");
    024:    }
    025:    public int Sum(int a, int b)
    026:    {
    027:           return a+b;
    028:    }
    029: }




    using System;
    002: delegate void deleMath(int Value); //델리게이트 선언
    003: class MainClass
    004: {
    005:    static void Main(string[] args)
    006:    {
    007:           //Math클래스 선언및 인스턴스화
    008:           MathClass MathClass=new MathClass();
    009:        
    010:           //델리게이트 선언및 인스턴스화(덧셈)
    011:           deleMath Math=new deleMath(MathClass.Plus);
    012:
    013:           //위임연산(뺄셈,곱셈추가)
    014:           Math+=new deleMath(MathClass.Minus);
    015:           Math+=new deleMath(MathClass.Multiply);
    016:           //결과1
    017:           MathClass.Number=10;
    018:           Math(10);
    019:           Console.WriteLine("Result:{0}",MathClass.Number);
    020:
    021:           //위임연산(뺄셈제거)
    022:           Math-=new deleMath(MathClass.Minus);
    023:           //결과2
    024:           MathClass.Number=10;
    025:           Math(10);
    026:           Console.WriteLine("Result:{0}",MathClass.Number);
    027:
    028:           //위임연산(곱셈제거)
    029:           Math-=new deleMath(MathClass.Multiply);
    030:           //결과3
    031:           MathClass.Number=10;
    032:           Math(10);
    033:           Console.WriteLine("Result:{0}",MathClass.Number);
    034:
    035:    }
    036: }
    037: class MathClass
    038: {
    039:    public int Number;
    040:    public void Plus(int Value)//더하기
    041:    {
    042:           Number+=Value;
    043:    }
    044:    public void Minus(int Value)//빼기
    045:    {
    046:           Number-=Value;
    047:    }
    048:    public void Multiply(int Value)//곱하기
    049:    {
    050:           Number*=Value;
    051:    }
    052: }

    출처
    http://hoons.kr/Lecture/LectureMain.aspx?BoardIdx=61&kind=4&view=0

    2012년 4월 23일 월요일

    파일과 디렉토리




    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.IO;

    namespace ConsoleApplication1
    {
        class Program
        {
            static void Main(string[] args)
            {
                DriveInfo di = new DriveInfo(@"c:\");//드라이브
                Console.WriteLine(di.TotalFreeSpace);
                Console.WriteLine(di.VolumeLabel);
                DirectoryInfo dirInfo = di.RootDirectory;//
                Console.WriteLine(dirInfo.Attributes.ToString());

                FileInfo[] fileName = dirInfo.GetFiles("*.*");//드라이브의 모든 파일목록 불러오기

                foreach (FileInfo fi in fileName)//FileInfo 형의 참조 fi 를 선언함과동시에 fileName의 조각들로 초기화 한다.
                {
                    Console.WriteLine("{0}: {1}: {2}", fi.Name, fi.LastAccessTime, fi.Length);
                }

                DirectoryInfo[] dirInfos = dirInfo.GetDirectories("*.*");//드라이브의 모든 디렉토리 목록

                foreach (DirectoryInfo d in dirInfos)
                {
                    Console.WriteLine(d.Name);
                }

                string currentDirName = Directory.GetCurrentDirectory();

                Console.WriteLine(currentDirName);

                string[] files = Directory.GetFiles(currentDirName, "*.txt");

                foreach (string s in files)
                {
                    FileInfo fi = null;
                    try
                    {
                        fi = new FileInfo(s);
                    }
                    catch (FileNotFoundException e)
                    {
                        Console.WriteLine(e.Message);
                        continue;
                    }
                    Console.WriteLine("{0} : {1}", fi.Name, fi.Directory);
                }

                if (!System.IO.Directory.Exists(@"C:\Users\Public\TestFolder\"))
                {
                    System.IO.Directory.CreateDirectory(@"C:\Users\Public\TestFolder\");
                }

                System.IO.Directory.SetCurrentDirectory(@"C:\Users\Public\TestFolder\");

                currentDirName = System.IO.Directory.GetCurrentDirectory();
                Console.WriteLine(currentDirName);

                // Keep the console window open in debug mode.
                Console.WriteLine("Press any key to exit.");
                Console.ReadKey();

            }
        }
    }

    StreamWriter //파일에 쓸수있는 닷넷 객체.
    StreamReader//파일을 읽어오는 닷넷 객체.



    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.IO;

    namespace ConsoleApplication1
    {
        class Program
        {
            static void Main(string[] args)
            {
                string a = "123456789";
                string b;
                using (StreamWriter sw = new StreamWriter(@"D:\test\test.txt", true))
                {
                    sw.WriteLine(a);
                }
                //using 을 쓰면 파일을 직접닫지않아도됀다.
                // { }않의것을 처리후 자동으로 닫는다.
                using(StreamReader sr = new StreamReader(@"D:\test\test.txt"))

                {
                 
                    while ((b = b = sr.ReadLine()) != null)
                    {
                        Console.WriteLine(b);
                    }
                   
                }

            }
        }
    }

    2012년 4월 5일 목요일

    window form

    사용자가 폼의 크기를 바꾸지못하게하는 폼속성
    FormBorderStyle
    MaximizeBox

    2012년 4월 2일 월요일

    class 변수명 = new 생성자();

    class 변수명 = new 생성자();
    class 변수명;//class 복합데이타 타입의 변수가 생성이돼는데 참조형식이다.
    new 생성자()//힙에 인스턴스(실체)를 만들고 변수명이 이를 가리키게 한다.

    2012년 3월 19일 월요일

    작업할 폴더를 선택해서 작업할 파일목록을 불러오기


    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 System.IO;

    namespace WindowsFormsApplication1
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
            }

            private void button1_Click(object sender, EventArgs e)
            {
                folderBrowserDialog1.ShowDialog();
                string aa = folderBrowserDialog1.SelectedPath;

                if (Directory.Exists(aa))
                {
                    foreach (string f in Directory.GetFiles(aa))
                    {
                        listBox1.Items.Add(f);
                    }
                }
               
            }
        }
    }

    listbox에 지정경로의 파일목록을 불러온다.

    지정경로의 파일목록 가져오기

    using System.IO;if (Directory.Exists(path)){    foreach (string f in Directory.GetFiles(path))    {        // 리스트 박스나 기타 다른 반복된 작업 수행    }}


    위에서 파일 경로는 path에 지정하면 됨
    foreach 문에서 반복적으로 파일경로+파일명+파일확장자를 가져와서 처리할 수 있음


    출처
    http://redcarrot.tistory.com/37

    FolderBrowserDialog


    이 클래스는 폴더를 찾아보고, 만들고 경우에 따라 선택하도록 사용자에게 요구하는 방법을 제공합니다.이 클래스는 파일이 아닌 폴더를 선택할 수 있게 하려는 경우에만 사용합니다.폴더 찾아보기는 트리 컨트롤을 통해 수행됩니다.파일 시스템의 폴더만 선택할 수 있으며 가상 폴더는 선택할 수 없습니다.

    일반적으로 새 FolderBrowserDialog를 만든 후에 RootFolder를 찾아보기를 시작할 위치로 설정합니다.또는 SelectedPath를 처음에 선택될 RootFolder의 하위 폴더에 대한 절대 경로로 설정할 수도 있습니다.뿐만 아니라 Description 속성을 설정하여 사용자에게 추가 지침을 제공할 수도 있습니다.마지막으로 ShowDialog 메서드를 호출하여 사용자에게 대화 상자를 표시합니다.대화 상자가 닫히고 ShowDialog의 대화 상자 결과가 DialogResult.OK이면 SelectedPath는 선택된 폴더의 경로를 포함하는 문자열이 됩니다.

    ShowNewFolderButton 속성을 사용하여 사용자가 새 폴더 단추로 새 폴더를 만들 수 있는지 여부를 제어할 수 있습니다.

    FolderBrowserDialog는 모달 대화 상자이므로 이 대화 상자가 표시되면 폴더를 선택할 때까지 나머지 응용 프로그램을 사용할 수 없습니다.모달 대화 상자가 표시되면 대화 상자의 개체를 제외한 아무런 입력 작업(키보드 또는 마우스 클릭)도 수행할 수 없습니다.프로그램은 일반적으로 호출 프로그램에 대한 입력이 발생하기 전에 일부 사용자 동작에 대한 응답으로 대화 상자를 숨기거나 닫아야 합니다.



    2012년 3월 12일 월요일

    기본문법

    생성자


    class와 이름이 같고 public으로 선언 매소드와같이 매개변수를 가질수있지만 (안가질수도 있지만)
    반환형이 없다.
    new  를 이용해서 인스턴스 생성시 매개변수를 넘겨주어서 필드를 초기화 할수있다.


    class 변수명 = new 생성자();//생성자 메소드
    class 변수명;//class 복합데이타 타입의 변수가 생성이돼는데 참조형식이다.
    new 생성자()//힙에 인스턴스(실체)를 만들고 변수명이 이를 가리키게 한다.

    프로퍼티

    private string name;
    public string name
    {
         get{ return name;}
         set{ name = value;}
    }

    오버로딩(Overloading)

    메소드를 만들떼 같은 기능이지만 매개변수가 다를 경우 오버로딩 기능이 없을경우
    새로운 메소드를 만들어야한다.

    2012년 3월 2일 금요일

    static메소드

    public static void 메소드( )
    static 으로 메소드를 선언할경우 인스턴스를 통하지않아도 호출이 가능하다.

    static으로 서언 돼지않았다면 인스턴스를 통해야 메소드를 호출할수있다.

    2012년 2월 1일 수요일

    상수선언을 한꺼번에 하는 열거형

    enum 형이름 (자료형,생략가능하며 생략시에 int로 인식) {상수1, 상수2, 상수3...}

    열거형 데이터 타입 처럼 쓸수있다.(ex int double ...)
    열거형이름 변수이름 = 열거형이름.상수;
    ex) enum hmg_val {a1,a2,a3,a4}
    hmg_val hval = hmg_val.a1;

    결과 hval = a1

    클래스에서 열거형을 선언할떼 메소드 안에서 선언할수 없다.