티스토리 뷰

C#

4 Form

김윤지. 2023. 3. 29. 23:18

131장. 기본 컨트롤

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

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

        private void button1_Click(object sender, EventArgs e)
        {
            string name = string.Format(txt_name.Text);

            if (name == "")
                MessageBox.Show("이름을 입력하세요", "경고");
            else
                lbl_out.Text = name + "님! 반갑습니다!";
        }
    }

버튼을 클릭했을 때 문자열 name을 txt_name의 텍스트를 따와 지정하고

만약 name이 비어있다면 이름을 입력하라는 경고 메시지 박스를 띄우고

그렇지 않다면 lbl_out의 텍스트를 name님 반갑습니다! 로 출력한다

 

 

 

130장. 메시지박스

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

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

        private void Form1_Load(object sender, EventArgs e)
        {
            MessageBox.Show("간단한 메시지 박스 입니다");
            MessageBox.Show("제목 표시 메시지 박스입니다", "제목");
            DialogResult result1 = MessageBox.Show("배경색을 변경할까요", 
                "Question", MessageBoxButtons.YesNo);   //메시지박스 결과를 result1에 저장
            if (result1 == DialogResult.Yes)
                this.BackColor = Color.Yellow;
        }
    }
}

간단한 메시지 박스, 제목 표시 메시지 박스를 띄우고

DialogResult : 식별자 지정

result1이라는 식별자에 메시지박스의 결과를 지정한다.

만약 result1이 yes라면 this(Form1)의 배경색을 노랑으로 변경

 

 

132장. 레이블에서 여러 줄 출력

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

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

        private void Form1_Load(object sender, EventArgs e)
        {
            label1.Text = "";
            label2.Text = "";
            button1.Text = "라파엘로, 아테네 학당";
            this.Text = "Label Control";
        }

        private void button1_Click(object sender, EventArgs e)
        {
            label1.Text = "라파엘로";
            label2.Text = "르네상스 시대의 거장인 라파엘로 산치오가 교황 율리오 2세의 주문으로 27세인 1509~1510년에 바티칸 사도 궁전 내부의 방들 가운데서 교황의 개인 서재인 '서명의 방(Stanza della Segnatura)'에 그린 프레스코화.\n" +
                "서명의 방의 네 벽면은 각각 철학, 신학, 법, 예술을 주제로 " +
                "벽화가 그려졌는데 이중에서 아테네 학당은 철학을 상징하는 " +
                "그림이다.가로 823.5cm, 세로 579.5cm 크기의 벽면에 모두 54명의 철학자가 배치되어 있다. 철학자들이 모여서 토론하고 있는 공간은 이 벽화가 그려질 당시 도나토 브라만테가 설계해 막 공사에 착수한 성 베드로 대성당의 내부를 모티브로 1점 투시도법을 사용해 묘사되었다. 벽기둥 양쪽에 있는 두 석상은 왼쪽이 아폴론, 오른쪽이 아테나이다. 아폴론과 아테나는 이성과 지혜를 상징하는 신이므로 그림의 의미에 적합한 소재라 할 수 있다.";
        }
    }
}

label2의 AutoSize 속성을 False로 설정하고 영역 조정

 

 

 

134장. 체크박스

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

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

        private void button1_Click(object sender, EventArgs e)
        {
            string states = "";
            CheckBox[] cBox = {checkBox1, checkBox2, checkBox3,
                checkBox4, checkBox5};

            foreach (var c in cBox) 
            {
                states += string.Format("{0} : {1}\n",
                c.Text, c.Checked);
            }

            MessageBox.Show(states, "Check States");

            String summary = "좋아하는 과일은 ";
            foreach (var c in cBox)
            {
                if (c.Checked /*== true*/) 
                    summary += c.Text + " ";
            }
            MessageBox.Show(summary, "summary"); 
        }
    }
}

선택된 과일을 저장할 문자열 states 변수 생성

체크박스 배열 cBox 생성하고 5개의 체크박스로 초기화

 

foreach cBox에 있는 c 요소에 대해 Text속성과 Checked속성을 states 문자열에 추가

메시지박스에 states를 출력한다

 

summary라는 문자열 생성

foreach cBox에 있는 c요소에 대해 만약 c가 체크되어있거나 true라면 summary에 c의 Text값을 추가

메시지박스에 summary를 출력한다

 

 

135장. 라디오버튼과 그룹박스

 

라디오버튼 : 여러 항목 중 한 개의 항목만을 선택 할 때, 일반적으로 그룹박스와 함께 사용

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

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

        private void button1_Click(object sender, EventArgs e)
        {
            string result = "";
            if (rbKorea.Checked)
                result = "국적 : 대한민국\n";
            else if (rbChina.Checked)
                result = "국적 : 중국\n";
            else if (rbJapan.Checked)
                result = "국적 : 일본\n";
            else if (rbOthers.Checked)
                result = "국적 : 그 외\n";

            if (rbMale.Checked)
                result += "성별 : 남자";
            else if (rbFemale.Checked)
                result += "성별 : 여자";
            MessageBox.Show(result, "Result");
        }
    }
}

버튼을 클릭했을 때

결과를 저장하는 문자열 result를 생성하고

rb(국가)가 Checked라면 result를 국적에 맞게 수정

rb(성별)이 Checked라면 result에 성별을 추가

메시지박스에 result를 출력

 

 

137장. 성적계산기

결과 그룹박스 내에 있는 텍스트 박스의 ReadOnly 속성 true로 변경(내용 수정 방지)

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

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

        private void button1_Click(object sender, EventArgs e)
        {
            double sum = Convert.ToDouble(txtKor.Text)
                + Convert.ToDouble(txtMath.Text) 
                + Convert.ToDouble(txtEng.Text);

            double avg = sum / 3;
            txtSum.Text = sum.ToString();
            txtAvg.Text = avg.ToString("0.00");
        }
    }
}

총합을 저장하는 sum에 각 과목 텍스트박스의 Text값을 double로 형변환(Convert)해 더해서 저장한다

평균을 저장하는 avg를 sum을 3으로 나눠 저장한다

각 텍스트박스에 sum과 avg를 String으로 형변환해 저장한다

(평균은 소수점 둘째자리까지 출력해준다)

 

 

43장. 반복문

<반복문의 문법>

- while

- do while

- for

 - foreach(배열, 컬렉션과 함께 사용)

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

namespace _012_for_1_100
{
    internal class Program
    {
        static void Main(string[] args)
        {
            //43장. 1~100의 합
            int sum = 0;
            for (int i = 1; i <= 100; i++)
                sum += i;
            Console.WriteLine("1~100의 합 : {0}", sum);


            //1~100까지 홀수의 합
            sum = 0;
            for(int i = 1; i <= 100; i++)
                if (i % 2 == 0)
                    sum += i;
            Console.WriteLine("1~100까지 홀수의 합 : {0}", sum);
            

            //1~100까지 역수의 합
            double rsum = 0;
            for (int i = 1; i <= 100; i++)
                rsum += 1.0 / i;
            Console.WriteLine("1~100까지 역수의 합 : {0:F2}\n", rsum);


            //45장. 구구단
            Console.Write("구구단의 단을 입력 : ");
            int x = int.Parse(Console.ReadLine());
            for (int i = 1; i <= 9; i++)
                Console.WriteLine("{0}x{1}={2}", x, i,x*i);
            Console.WriteLine("");


            //47장. n의 m승 구하기
            Console.Write("n 입력 : ");
            int n = int.Parse(Console.ReadLine());
            Console.Write("m 입력 : ");
            int m = int.Parse(Console.ReadLine());
            int exp = 1;
            for (int i = 1; i <= m; i++)
                exp *= n;
            Console.WriteLine(exp);
            Console.WriteLine("");


            // 53장. 팩토리얼 (k! = 1*2*3*4*...k)
            Console.Write("구하고자 하는 팩토리얼 입력 : ");
            int k = int.Parse(Console.ReadLine());
            int fact = 1;
            for (int i = 1;i <= k; i++)
                fact *= i;
            Console.WriteLine("{0}의 팩토리얼 = {1}", k, fact);
        }
    }
}
1~100의 합 : 5050
1~100까지 홀수의 합 : 2550
1~100까지 역수의 합 : 5.19

구구단의 단을 입력 : 3
3x1=3
3x2=6
3x3=9
3x4=12
3x5=15
3x6=18
3x7=21
3x8=24
3x9=27

n 입력 : 5
m 입력 : 3
125

구하고자 하는 팩토리얼 입력 : 5
5의 팩토리얼 = 120

 

57장. 배열

<C/C++>

- int a[10];

- int a[] = {1, 2, 3};

 

<C#>(Array 클래스)

- int[] a = new int[10];

- int[] a = new int[] {1, 2, 3};

- int[] a = {1, 2, 3};

 

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

namespace _013_arr
{
    internal class Program
    {
        static void Main(string[] args)
        {
            int[] a = new int[10];  //10개의 정수를 읽어서 배열에 저장

            for (int i = 0; i < 10; i++)
                a[i] = int.Parse(Console.ReadLine());

            for (int i = 0; i < 10; i++)
                Console.Write(a[i] + " ");
            Console.WriteLine();

            foreach (var x in a)
                Console.Write(x + " ");
            Console.WriteLine();
        }
    }
}
1
5
3
4
6
7
33
52
12
64
1 5 3 4 6 7 33 52 12 64
1 5 3 4 6 7 33 52 12 64

10개의 정수를 읽는 새 배열을 만든다

i를 0부터 9까지 10번을 반복하며 배열 a의 i 인덱스에 정수를 받아 지정한다

각 for문과 foreach문을 이용해 배열을 출력한다

 

 

61장. Random 클래스

<클래스 객체 생성>

- 클래스이름 객체이름 = new 클래스이름();

- Random r = new Random();          //Random 클래스의 객체 r을 생성

- Button btn = new Button();            //Button 클래스의 객체 btn을 생성

 

<객체의 활용>

- 클래스의 속성과 메소드를 사용

- r.Next();               // 0~20억 사이의 값

- r.Next(100);         // 0~99 사이의 값

- r.Next(1,7);          // 1~6 사이의 값

- r.NextDouble();   // 0에서 1.0 미만의 값

 

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

namespace _014_Class
{
    internal class Program
    {
        static void Main(string[] args)
        {
            Random r = new Random();

            for(int i  = 0; i < 10; i++)
                Console.WriteLine(r.Next(10));
            Console.WriteLine();

            //10명의 성적을 저장하는 배열 score, 랜덤으로 정수 생성 후 저장
            int[] score = new int[10];

            for (int i = 0; i < 10; i++)
                score[i] = r.Next(101);

            foreach(int S in score)
                Console.Write("{0}점 ", S);
        }
    }
}
2
5
7
0
0
8
9
8
8
5

98점 95점 64점 82점 46점 67점 92점 80점 2점 53점

Random r 을 생성해 r에 10 미만의 수를 10번 반복해 출력한다

 

10칸짜리 score 배열을 생성해

score의 i인덱스에 1~100의 수를 랜덤으로 10번 지정해 foreach문을 이용해 출력한다

 

 

 

62장. 배열에서 최소, 최대, 평균 계산

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

//외워

namespace _015_min_max
{
    internal class Program
    {
        static void Main(string[] args)
        {
            Random r = new Random();
            int[] a = new int[10];

            int sum = 0;

            for (int i = 0; i < 10; i++)
                a[i] = r.Next(101);
            int min = a[0];
            int max = a[0];

            for (int i = 0; i < 10; i++)
            {
                if (a[i] < min)
                    min = a[i];
                if (a[i] > max)
                    max = a[i];
                sum += a[i];
            }
            Console.WriteLine("최대값 : {0} 최소값 : {1} 평균 : {2}", max, min, sum/10.0);
        }
    }
}
최대값 : 99 최소값 : 17 평균 : 59.2

Random r과 10칸의 배열 a를 생성한다

합을 지정할 변수 정수 sum을 0으로 초기화한다

배열 a의 i인덱스에 100까지의 정수를 10번 지정한다

a배열의 0인덱스를 각 min, max로 지정한다

 

for문을 이용해 인덱스 0~9번동안 a[i]와 min, max값을 비교하며

만약 a[i]가 min, max보다 작거나 크면 min, max 값을 a[i]로 바꾼다

총합 sum에 a[i]를 더해 출력한다(평균은 sum/3)

 

 

170장. Chart 컨트롤 사용

<Chart 용어>

- Chart 컨트롤

- ChartArea : 차트가 그려지는 영역

   > 하나의 차트 컨트롤은 하나 이상의 ChartArea를 갖는다

- Series : 데이터

   > 하나의 ChartArea에는 하나 이상의 Series를 갖는다

- Legends : 범례

- Titles : 차트 제목

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

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

        private void Form1_Load(object sender, EventArgs e)
        {
            chart1.Titles.Add("성적");
            Random r = new Random();

            for (int i = 1; i <= 10; i++)
                chart1.Series[0].Points.Add(r.Next(101));
                //chart1.Series[0].Points.Add(i*10);

            chart1.Series[0].LegendText = "비주얼\n프로그래밍";
        }
    }
}

chart1의 제목을 성적으로 설정한다

Random r을 생성한다

chart1의 Series[0] 시리즈에 랜덤하게 점수를 추가한다

chart1의 Series[0] 시리즈의 범례를 "비주얼프로그래밍"으로 바꾼다

 

 

171장. 두 개의 차트 영역, 두 개의 시리즈 활용하기

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Windows.Forms.DataVisualization.Charting;

namespace _016_chart2
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            this.Text = "Chart Control";        //Form1의 제목 변경
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            chart1.Titles.Add("성적");          //chart1의 제목 변경

            //시리즈1은 디폴트로 존재하므로 시리즈2 하나만 추가하면 됨
            chart1.Series.Add("Series2");

            chart1.Series[0].LegendText = "수학"; //시리즈[0]의 범주 변경
            chart1.Series[1].LegendText = "영어"; //시리즈[1]의 범주 변경

            Random r = new Random();              //랜덤생성
            for(int i=1; i<=10; i++)              //시리즈1, 2에 100까지의 수 10개 생성  
            {
                chart1.Series[0].Points.AddXY(i, r.Next(101));      //AddXY = x축 y축
                chart1.Series[1].Points.AddXY(i, r.Next(101));

            }
        }

        private void btn2chart_Click(object sender, EventArgs e)    //나누어 표시 버튼이 클릭되면
        {
            if (chart1.ChartAreas.Count == 1)                       //만약 ChartArea가 1개라면
                chart1.ChartAreas.Add("ChartArea2");                //ChartArea에 ChartArea2 추가
            chart1.Series[1].ChartArea = "ChartArea2";              //Series[1]의 ChartArea를 ChartArea2로 변경

        }

        private void btn1chart_Click(object sender, EventArgs e)    //합쳐서 표시 버튼이 클릭되면
        {
            if (chart1.ChartAreas.Count == 2)                       //만약 ChartArea가 2개라면
                chart1.ChartAreas.RemoveAt(1);                      //ChartArea2를 삭제한
            chart1.Series[1].ChartArea = "ChartArea1";              //Series[1]의 ChartArea를 ChartArea1로 변경
        }
    }
}

(코드에 주석으로 설명)

'C#' 카테고리의 다른 글

6 Firebase  (0) 2023.04.13
5 함수, 타이머  (0) 2023.04.05
3 반복문 예제 30개  (0) 2023.03.22
2주차  (0) 2023.03.15
1주차 BMI 계산기 만들기  (0) 2023.03.07
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
TAG
more
«   2024/09   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30
글 보관함