티스토리 툴바




리피터 엑셀 다운로드
 public void RptToExcel(System.Web.UI.WebControls.Repeater repeater, string filename)
 {
        repeater.EnableViewState = false;

        System.IO.StringWriter sw= new System.IO.StringWriter();
        System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(sw);
        repeater.RenderControl(hw);

        ExportExcel(sw, filename);
 }
private void ExportExcel(System.IO.StringWriter sw, string filename)
{
        Response.ContentType = "application/vnd.ms-excel";
        Response.AddHeader("Content-Disposition", "attachment;filename="
        + string.Concat(DateTime.Now.ToString("yyyyMMddHHmmss"), ".xls"));
        Response.Charset = "ks_c_5601-1987";
        string data = @"<html><head><style>.text {mso-number-format:\@;} </style>
       <meta http-equiv='content-type' content='text/html; charset=utf-8'></head><body>";
       data += System.Text.RegularExpressions.Regex.Replace(sw.ToString(), "&nbsp;", " ");
        data += "</body></html>";

        Response.Write(data);
        Response.End();
}


rptExcel.DataSource = ds.Tables[0];
rptExcel.DataBind();
rptExcel.Visible = true;
RptToExcel(rptExcel, "name.xls");
rptExcel.Visible = false;

'정리없는자료 > .NET' 카테고리의 다른 글

ASP.NET ( C# ) Socket 통신, w3Sockets  (0) 2011/04/21
IIS7.x에서 파일 업로드 용량 변환  (0) 2010/11/12
repeater Excel download  (0) 2010/11/12
Repeater FooterTemplate  (0) 2010/11/12
ASP.NET 특정 일자를 가감  (0) 2008/10/15
ASP.NET 정상적인 일자인지를 체크  (0) 2008/10/15

top

Trackback Address :: http://deuxist.tistory.com/trackback/493 관련글 쓰기

Write a comment



네이트온 메신져에 보면 미니창 투명도를 조절하여 은밀한 대화를 나눌수가있죠.

폼에 트랙바 하나와 라벨을 올립니다.
트랙바를 더블클릭하여 다음과 같이 작성합니다.

private void trackBar_Scroll(object sender, EventArgs e)
{
          
          int num = 0;
        num = int.Parse(this.trackBar.Value.ToString()) * 10;
        this.lbBar.Text = num.ToString();
          //lbBar 라벨
          this.Opacity = 1.0 - (this.trackBar.Value / 12.0);
}

간단하죠~^^;


top

Trackback Address :: http://deuxist.tistory.com/trackback/443 관련글 쓰기

Write a comment



잘 정리되있는 자료가있군요.^^;

1. 홀수행을 다른 색으로 보여주고 싶을 때


행마다 특정 배경색을 입혀보고 싶은 분들은 다음과 같이 구현하시면 됩니다. 일단 홀수행을 기준으로 설명하자면 AlternatiogRowsDefaultCellStyle속성에 BackColor를 선언하여 색상을 지정하시면 됩니다.

dbView.AlternatingRowsDefaultCellStyle.BackColor = Color.Aqua;

2. 여러개의 열이나 행을 선택하지 못하도록 막고 싶을 때

기본적으로 여러개의 열과 행을 선택할 수 있는데 이를 막고 한개의 열이나 한개의 행만 선택하도록 하고 싶을 때 다음과 같이 선언하면 됩니다.

dbView.MultiSelect = false;

3. 행단위로 클릭하도록 만들고 싶을 때

기본적으로 열단위로 클릭하도록 처리되어 있는데 이를 행단위로 클릭할 수 있는 기능도 있습니다. 이 기능은 SelectionMode속성에 DataGridViewSelectionMode.FullRowSelect를 설정하면 간단하게 됩니다.

dbView.SelectionMode = DataGridViewSelectMode.FullRowSelect;

참고로 DataGridViewSelectMode열거체이외의 값도 설정하여 열단위로 선택기능을 구현할 수 있고 열단위로 선택기능을 사용시 각 열에 대한 SortMode속성이 Automatic값(기본)으로 설정이 안되어 있으면 사용할 수 없습니다.

4. 행번호 보여주고 싶을 때

각 행의 행번호를 보여주고 싶을 때에는 행을 화면에 보여주는 타이밍인 RowPostPaint이벤트 타이밍에 그 행의 인덱스번호+1형태로 행헤더의 열 안에 넣어주면 끝납니다.

RowPostPaint이벤트핸들러의 2번째 파라미터인 DataGridViewRowPostPaintEventArgs 객체로부터 보여주기 위해 필요한 Graphics객체나 좌표값을 얻을 수 있습니다.

이하 e변수로 받을 수 있는 객체에 대해서 알아보면 다음과 같습니다.

<DataGridViewRowPostPaintEventArgs 객체>
  * e.Graphics - Graphics객체
  * e.RowIndex - 표시중인 행번호 (0부터 시작하기 떄문에 +1필요)
  * e.RowBounds.X 행헤더 열 왼쪽 위 X좌표
  * e.RowBounds.Y 행헤더 열 왼쪽 위 Y좌표
  * e.RowBounds.Height 행헤더 열높이
  * dbView.RowHeadersWidth 행헤더 셀 폭
  * dbView.RowHeadersDefaultCellStyle.Font 사용폰트
  * dbView.RowHeadersDefaultCellStyle.FontColor 폰트 색상
 
private void dbView_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e) {

     // RowPointPaint 이벤트핸들러
     // 행헤더 열영역에 행번호를 보여주기 위해 장방형으로 처리
     Rectangle rect = new Rectangle(e.RowBounds.Location.X,

                         e.RowBounds.Location.Y,

                         dbView.RowHeadersWidth - 4,

                         e.RowBounds.Height);
     // 위에서 생성된 장방형내에 행번호를 보여주고 폰트색상 및 배경을 설정
     TextRenderer.DrawText(e.Graphics,

                         (e.RowIndex + 1).ToString(),

                         dbView.RowHeadersDefaultCellStyle.Font,

                         rect,  

                         dbView.RowHeadersDefaultCellStyle.ForeColor,

                         TextFormatFlags.VerticalCenter | TextFormatFlags.Right);

}


5. 특정 행이나 열을 고정시키고 스크롤하지 못하도록 막고 싶을 때

여기서는 2번째 열을 고정시킨 경우를 보여주고 있는데 그리드를 옆으로 스크롤 할 경우 3번째 열보다 우측의 스크롤이 나오고 1번째열과 2번째열은 고정된 형태를 보여줍니다.

- Frozen 속성 : 열 고정시키기 위한 속성으로 이를 고정시키기 위한 열을 지정하고 true값을 선언하면 해당 열의 좌측 열은 전부 고정되어 스크롤 할 없게 됩니다.

dbView.Columns[1].Frozen = true;

- DividerWidth 속성 : 구분선 폭 변경을 할 때 사용하는 속성으로서 이를 통해서 2번째열과 3번째열 사이 구분선을 약간 두껍게 표현하여 보다 직관적으로 구분할 수 있습니다.

dbView.Columns[1].DividerWidth = 3;


6. 그리드 실행될 때 기본 열이 선택된 모습을 보여주고 싶지 않을 때

아주 간단하게 속성하나만 선언하면 되는데 이때 주의해야할 점은 폼_Load이벤트핸들러에서는 효과가 없다는 것입니다. 어느 열도 선택되지 않는 상태로 보여주기 위해서는 폼이 표시된 이후 한번만 발생하는 폼_Shown 이벤트핸들러에서 선언해주는 것이 좋습니다.

        private void Form1_Shown(object sender, EventArgs e)
        {
            //6. 그리드 실행될 때 기본 열이 선택된 모습을 보여주고 싶지 않을 때
            dbView.CurrentCell = null;
        }


7. 특정값을 가진 열을 좀 다르게 보여주고 싶을 때

특정값을 가진 열을 좀더 강조하여 보여주고 싶은 경우가 종종 생깁니다. 이럴 때 유용한 것으로 예제에서는 Bike란 단어가 포함된 열인 경우 빨간색으로 글씨를 보여주도록 설정하였습니다.

특히, 개별적인 열에 대해서 보여주기 위해서는 폼_CellFormating이벤트핸들러를 이용하면 될것같습니다. 본래 이 이벤트핸들러는 특정값을 가진 열의 독립적인 서식을 적용하기 위한 것으로 열 스타일만 변경할 수 있습니다.

CellFormmating이벤트핸들러의 2번째파라미터로 받는 DataGridViewCellFormattingEventArgs객체로부터 그 열의 현재 스타일이나 열의 값을 얻거나 설정할 수 있습니다. 즉, 이것을 통해 열의 값을 확인하고 그 스타일을 변경하는 형태로 개발을 해보려고 합니다. 또한, 이벤트 발생시 열위치는 ColumnIndex속성과 RowIndex속성으로 알 수 있습니다.

private void dbView_CellFormatting(object sender,

DataGridViewCellFormattingEventArgs e) {
{

      // 7. 특정값을 가진 열을 좀 다르게 보여주고 싶을 때
      if (e.ColumnIndex == 1)
      {
            if (e.Value != null)
            {
                 string text = e.Value.ToString();
                 if (text.Contains("Bike"))
                 {
                      e.CellStyle.ForeColor = Color.Red;
                      e.CellStyle.SelectionForeColor = Color.Red;
                  }
              }
         }
  }

8. 헤더열이나 헤더행의 색을 변경하고 싶을 때

헤더행과 헤더열의 색을 변경하고싶은 경우에는 ColumnHeadersDefaultCellStyle속성과 RowHeadersDefaultCellStyle속성을 사용하면 괜찮을 것같습니다.

dbView.ColumnHeadersDefaultCellStyle.BackColor = Color.RosyBrown;
dbView.RowHeadersDefaultCellStyle.BackColor = Color.SeaGreen;

단, 위와 같이 선언하여도 그것이 사용할 수 없는 경우가 있는데 이것은 애플리케이션이 적용하고 있는 Windows XP의 Visual 스타일을 우선적으로 사용하기 때문인데 이 코드는 윈폼을 만들 때 자동으로생성하기 때문에 Application클래스의 EnableVisualStyles메소드를 호출합니다.

dbView.EnableHeadersVisualStyles = false;

그외 열과 행의 사이에 있는 선스타일을 변경할 수 있는데 다음과 같이 선언하게 되면 한개의 라인으로 보여주게 됩니다.

dbView.RowHeadersBorderStyle = DataGridViewHeaderBorderStyle.Single;
dbView.ColumnHeadersBorderStyle = DataGridViewHeaderBorderStyle.Single;

9. 선택한 행이나 열에 대한 값을 확인하고 싶을 때

보통 특정 행을 추가하거나 삭제하고 편집도 하는데 이럴 때 선택된 행이나 열에 대해서 어떤 조작을 하는 경우도 많습니다. 그래서 이번에는 이를 간단하게 처리하는 방법에 대해서 정리해보았습니다. 이 부분에 대한 것을 사용형태만 설명하고 넘어가겟습니다.

아래에서 설명한 것들중에서 같은 클래스명이나 속성명이 Row가 들어가거나 Column이란 단어로 비교되는 것을 알 수 있는데 이것에 의해 열에 대한 행과 똑같은 조작을 할 수 있다는 것을 알 수 있습니다.

- 선택된 열 얻기 : SelectedCells 속성

현재 선택된 열은 SelectedCells속성으로 얻을 수 있고 그리드에서 여러개의 열을 동시에 선택할 수 있기 때문에 이 속성은 DataGridViewSelectedCellCollection클래스 객체로 되어 잇습니다. 여기서는 간단하게 하나의 열을 조작할 경우에 사용되는 형태를 보여줍니다.

foreach (DataGridViewCell cell in dbView.SelectedCells) { }

선택된 열 갯수 얻기을 얻어 위에서 선택된 열을 얻을 수 있는 방법도 있습니다.

SelectedCells.Count

for(int i=0; i<dbView.SelectedCells.Count; i++) { }

또한 MultiSelect속성을 false를 설정한 것은 사용자가 여러개의 행/열을 선택할 수 있도록 할 수 있습니다.

- 선택된 행 얻기 : SelectedRows 속성

행을 선택하여 행정보를 얻는 경우에 필요한 것으로 DataGridViewRow클래스의 객체의 컬렉션은 Selectedows속성으로 얻을 수 있습니다.

foreach(DataGridViewRow row in dbView.SelectedRows) { }

- 특정 셀이나 행이 선택되었는지 확인하는 경우 : Selected 속성

셀이 선택되었다면 true, 셀이 선택되지 않았다면 false로 결과를 보내줍니다.

dbView[x,y].Selected;

특정 행이 선택되었는지 확인하는 경우

dbView.Rows[n].Selected;

- 선택된 행이나 열 설정

데이터 새로고침등의 이벤트로 인해 데이터를 새롭게 보여줄때 현재 위치를 나타내고 싶은 경우에 필요한 것으로 (x,y)위치에 있는 열을 선택한 상태로 두고 싶다면 다음과 같이 선언합니다.

dbView[x,y].Selected = true;

n행의 행을 선택한 상태로 두고 싶은 경우에는 아래와 같이 선언합니다.

dbView.Rows[n].Selected = true;

- 모든 선택된 열을 지울 때 : ClearSelection 메소드

 
10. 열에 보여지는 문자열을 여러행으로 보여주고 싶을 때

열에 표시되는 문자열이 길게 되면 한줄로 보여주지만 오버되면 잘려서 안보여줍니다. 이는 열스타일의 WrapMode속성을 DataGridViewTriState.True(그외 False, NotSet)로 설정하여 셀크기안에서 오버되면 여러행으로 해당 텍스트등을 모두 보여줍니다.

그리드안의 모든 열을 여러행을 보여주고 싶다면, DefaultCellStyle속성의 WrapMode속성에 DataGridViewTriState.True를 설정하는 것을 권장합니다. 이렇게하면 정말 간단하게 구현이 됩니다. ^^

또한, 다음줄로 넘어간 문자열이 발생하면 행의 높이는 자동으로 조절되는데 AutoSizeRowMode속성에 DataGridViewAutoSizeRowsMode.AllCells를 설정할 것을 권장합니다. 이상 이 두가지를 정리하면 다음과 같습니다.

dbView.DefaultCellStyle.WrapMode = DataGridViewTriState.True;
dbView.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCells;

 

11. 맨 밑까지 스크롤하고 싶을 때

보통 맨 밑에 있는 행을 합계로 보여주거나 응용프로그램 실행시 곧바로 사용자가 새 행을 추가할 있도록 하는 경우가 있는데 이럴때 그리드 맨밑까지 스크롤을 가볍게 해줄 필요가 있습니다. 열단위 표시를 스크롤하기 위한 속성이 3가지가 있는데 다음과 같습니다.

<속성>

FirstDisplayedCell 그리드 왼쪽 위에 표시된 열 얻기/설정

FirstDisplayedScrollingColumnIndex 그리드에 표시된 처음 열 얻기/설정

FirstDisplayedScrollingRowIndex 그리에 표시된 처음 행 얻기/설정

예를 들어 [2,15]의 위치에 있는 열을 FirstDisplayedCell속성으로 설정하면 [2,15]위치의 열에 왼쪽위로 그리드가 스크롤된 상태로 보여집니다.

dbView.FirstDisplayedCell = dbView[2,15];

마지막 행을 표시하기 위해 그리드 맨밑까지 스크롤시키려면 FirstDisplayedScrollingRowIndex속성을 이용하길 권장합니다.

dbView.FirstDisplayedScrollingRowIndex = dbView.Rows.Count - 1;


12. 오토컴플릿 기능을 사용하고 싶을 때

텍스트박스 열은 열 편집 및 새 행을 추가시 텍스트박스를 사용합니다. 이럴때 열편집시 오토컴플릿 기능을 사용할 수 있다는 점입니다.

이는 열이 편집상태가 될 때 발생하는 EditingControlShowing이벤트핸들러가 발생할 때 보여주고 있는 텍스트박스 객체를 얻어 오토컴플릿에 필요한 속성을 설장하는 형태입니다.

실제 이 텍스트박스는 DataGridViewTextBoxEditingControl 클래스의 인스턴스를 만들어 TextBox클래스의 파생클래스로서 TextBox형으로 케스팅합니다.

이렇게 예고로 내놓은 코드는 모든 텍스트박스에 대한 오토컴플릿기능을 설정하고 있기 때문에 어느 열을 사용하더라도 오토컴플릿기능이 작동되며 특정열만 오토컴플릿 기능을 지정할 수도 있습니다. 이 예제에서는

 private void dbView_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
 {
        TextBox tb = e.Control as TextBox;
        if (tb == null)
        {
             return;
         }
        if (dbView.CurrentCell.ColumnIndex == 1)
        {
             tb.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
             tb.AutoCompleteSource = AutoCompleteSource.AllSystemSources;
         }
         else
         {
             tb.AutoCompleteMode = AutoCompleteMode.None;
         }
  }  

 
13. 열안에 문자열 선택하고 싶을 때

열 안에의 문자열을 선택하여 처리하고 싶다면 BeginEdit메소드를 사용하는 것을 권장합니다. 이 이름처럼 열을 편집하기 위한 것으로 파라미터값을 true로 선언하면 열 안의 문자열이 선택된 상태로 편집할 수 있습니다. 만약 false로 선언하면 커서가 문자열은 선택하지 않고 문자열끝에 커서가 있는 상태로 조작을 할 수 있습니다.

 

 // 폼_Load이벤트핸들러가 BeginEdit를 호출할 경우 폼을 먼저 표시할 필요가 있음
 this.Show();
 // 2행 1열 열을 현재 열로 지정
 dbView.CurrentCell = dbView[0, 1];
 // 현재 열을 편집상태로
 dbView.BeginEdit(true);

14. 왼쪽 윗 빈 열에 값 설정하고 싶을 때

왼쪽 맨 윗열은 항상 빈 여백의 열로 남아 있는데 여기에 특정한 표시를 나타내기 위해 값을 넣거나 열 스타일을 변경할 수 있습니다.

이 빈열은 DataGridView컨트롤의 TopLeftHeaderCell속성으로 접근할 수 있고 이 속성값은 헤더 행이나 헤더 열과 동일한 DataGridViewHeaderCell클래스의 객체입니다. 일반적인 열을 나타내는 DataGridViewCell클래스를 상속받은 클래스입니다.

dbView.TopLeftHeaderCell.Value = "매장";

15. 오른쪽버튼 클릭시 열 선택을 할 수 있도록 하고 싶을 때

기본적으로 마우스 오른쪽버튼으로 클릭시 어떠한 조작도 제어되지 않습니다. 그래서 간단하게 클릭시 열을 선택할 수 있도록 하는 방법을 추가해보고자 합니다.

이는 CellMouseClick이벤트핸들러를 생성하여 열을 클릭시 Control클래스로 정의되어 있는 MouseClick이벤트가 추가되어 CellMouseClick이벤트핸들러가 발생하는 형태입니다. 이 이벤트핸들러의 파라미터로는 클릭된 열의 행번호와 열번호를 얻을 있어 클릭되어 진 열을 간단하게 접근하실 수 있습니다.

여기서 보여주는 스타일은 이벤트핸들러를 통해 클릭된 열의 선택상태를 알려주는 것을 아주 간단합니다.

 private void dbView_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e) {
      //오른쪽 버튼 클릭인가?
      if (e.Button == MouseButtons.Right) {
           // 헤더 이외의 열
          if (e.ColumnIndex >= 0 && e.RowIndex >= 0) {
               // 오른쪽 버튼 클릭된 열
               DataGridViewCell cell = dbView[e.ColumnIndex, e.RowIndex];
               cell.Selected = !cell.Selected; // 선택상태 반전
           }
      }

  }  

한가지더 알려드리자면, 두번째 파라미터 DataGridViewCellMouseEventArgs클래스는 MouseClick이벤트핸들러의 파라미터인 MouseEventArgs클래스의 파생클래스입니다. 이 클래스는 마우스의 위치나 클릭된 버튼 종류를 알려주며 클릭된 열의 행번호와 열번호를 리턴해주는 RowIndex속성과 ColumnIndex속성이 추가되어 있고 헤더용 열이나 행이 클릭된 경우 속성은 -1로 처리됩니다.


16. 행 삭제시 확인메세지를 보여주고 싶을 때

행을 선택하고 Del키를 누르면 행을 삭제할 수 있습니다. 이럴 때 행의 삭제시 확인 메세지박스를 보여주는 형태를 구현하고 싶은 분들이 있을 것입니다. 이를 한번 구현해보이도록 하겠습니다.

DataGridView컨트롤에서는 행이 삭제될 때 UserDeletingRow이벤트핸들러가 발생합니다. 따라서 이 타이밍에 확인 메세지박스를 보여주는 것을 좋을 것같습니다. 그리고 한가지 팁으로 여러개의 행을 선택하고 Del키를 누르면 선택되어 있는 각 행별로 UserDeletingRow이벤트핸들러가 발생합니다.

또한 이 UserDeletingRow이벤트핸들러의 두번째 파라미터는 DataGridViewRowCancelEventArgs객체의 Cancel속성을 true로 설정하여 행삭제를 취소할 수 있습니다.

 

private void dbView_UserDeletingRow(object sender, DataGridViewRowCancelEventArgs e) {
       if (MessageBox.Show("삭제하시겠습니까?",

                                 "지정한 행삭제",

                                 MessageBoxButtons.YesNo) == DialogResult.No)
       {
             e.Cancel = true; //삭제 취소
       }
 }  


17. 열 순서를 마음대로 바꾸고 싶을 때

가끔 고객의 요구로 인해 열을 사용자가 원하는 순서대로 배치하고 싶은 경우가 나옵니다.
보통 열 순서변경은 마우스로 열 헤더를 드래그&드롭하여 처리할 수 있습니다.

AllowUserToOrderColumns속성을 true로 하면 간단하게 끝납니다.

dbView.AllowUserToOrderColumns = true;

http://blog.naver.com/gboarder 이곳에서 퍼온 http://blog.naver.com/kdllee 이분의 사이트에서 가져왔어요.

'정리없는자료 > .NET' 카테고리의 다른 글

ASP.NET string[]를 받아서 구분자로 구분, 문자열 리턴  (0) 2008/10/14
C# 폼 투명도 조절  (0) 2008/01/06
C# DataGridView 활용  (0) 2007/12/22
C# ComboBox에 이미지넣기  (0) 2007/12/22
비주얼스튜디오 단축키  (0) 2007/12/20
C# 위임(Delegate)  (0) 2007/12/15

top
TAG .NET, c#, C#.NET

Trackback Address :: http://deuxist.tistory.com/trackback/442 관련글 쓰기

Write a comment



여러개의 메서드를 동시에 호출한 것처럼 처리하기위해 위임(Delegate)형을 사용한다.
위임형은 delegate 키워드를 이용하여 선언한다.
public delegate void 위임이름(인수);

간단한 형태만알아보기 위해서 소스일부생략
public delegate void MyDelegate();
class MyClass{public void MyMethod(int x, int y)}
class MClass{
static void Main(){
MyClass mc = new MyClass();
//MyClass클래스의 인스턴스 mc를 생성합니다.
MyDelegate md = new MyDelegate(mc.MyMethod);
//mc.MyMethod메서드를 MyDelegate의 생성자에 인자 값으로 입력해서 MyDelegate형 md를 생성합니다.
md(3,4);
//위임형 md에 3,4를 입력해서 호출합니다.
}}

다중 위임 및 제거를 위해서는 +=연산자와 -=연산자를 이용한다.
md += new MyDelegate(mc.MyMethod);
md -= new MyDelegate(mc.MyMethod);

ex1)
public delegate void Mydelegate(string message);

    class Program
    {
        //static Mydelegate md = null;
        static event Mydelegate md = null;
        static void Main(string[] args)
        {
            Program p = new Program();
            string message = "한국";
            //p.OnDisplayMessage(message);
            //p.OnDisplayMessage(message);
            //Mydelegate md = null;
                md += new Mydelegate(p.OnDisplayMessage);
                md += new Mydelegate(p.OnDisplayMessage);
                md += new Mydelegate(p.NewOnDisplayMessage);
                //md(message);
                p.CallDelegate(md, message);
                md -= new Mydelegate(p.OnDisplayMessage);
                md -= new Mydelegate(p.OnDisplayMessage);
                if (md != null)
                {
                    md(message);
                }

        }
        private void CallDelegate(Mydelegate md, string msg)
        {
            md(msg);
        }
        private void OnDisplayMessage(string message)
        {
            Console.WriteLine(message);
        }
        private void NewOnDisplayMessage(string message)
        {
            Console.WriteLine(message+"메세지");
        }

    }




'정리없는자료 > .NET' 카테고리의 다른 글

C# ComboBox에 이미지넣기  (0) 2007/12/22
비주얼스튜디오 단축키  (0) 2007/12/20
C# 위임(Delegate)  (0) 2007/12/15
C# 스레드(thread)  (0) 2007/11/15
C# 윈도우 프로그래밍 예제파일  (0) 2007/11/14
C# Array for문 규칙  (0) 2007/11/13

top

Trackback Address :: http://deuxist.tistory.com/trackback/422 관련글 쓰기

Write a comment



Thread를 선언하기위해 System.Threading 네이스페이스를 추가합니다.
using System.Threading;

Thread의 주요 속성 및 메서드
Priority - 스레드의 우선순위를 나타내는 값을 가져오거나 설정
Abort() - 스레드를 종료하는 메서드
Sleep() - 지정된 수의 밀리초 동안 스레드 수행 중지
Start() - 스레드를 시작하는 메서드

ex1)
public static void Method(){}
static void Main(string[] args){
ThreadStart ts = new ThreadStart(Method);
//Thread 클래스의 생성자에 입력할 ThreadStart 위임형을 생성합니다.
Thread t1 = new Thread(ts);
//ThreadStart 위임형 ts를 인자로 입력해서 Thread형 t1를 생성합니다.
t1.Start();
//Thread형 객체 t1를 실행합니다.
}

'정리없는자료 > .NET' 카테고리의 다른 글

비주얼스튜디오 단축키  (0) 2007/12/20
C# 위임(Delegate)  (0) 2007/12/15
C# 스레드(thread)  (0) 2007/11/15
C# 윈도우 프로그래밍 예제파일  (0) 2007/11/14
C# Array for문 규칙  (0) 2007/11/13
C# string  (0) 2007/11/13

top

Trackback Address :: http://deuxist.tistory.com/trackback/421 관련글 쓰기

  1. Tracked from 행복한 프로그래머 2010/01/22 11:02 삭제

    Subject: [C# ] 스레드 사용하기

    프로세스와 스레드에 대한 개념은 어떤 프로그래밍 언어라 하더라두 공통으로 적용이 되는 부분입니다. C#에서 스레드를 사용하는 방식은 파라미터(Parameter)가 있냐 없냐에 따라서 달라집니다. 파라미터(Parameter)가 없는 경우 파라미터가 없는 경우에는 간단합니다. Thread 객체를 선언해 주고, 정의하는 과정에서 ThreadStart 를 만들어주면서 스레드가 동작시킬 함수명을 적어주면 됩니다. 자 한번 볼까요? Thread th..

Write a comment



Console.WriteLine("2차원배열-----------------------------------");
            char[,]  cd = new char[4,64];
            for(int s = 0;s < 4; s++)
            {
                for(int t = 0; t < 64;t++)
                {
                    cd[s, t] = (char)(64*s+t);
                }
            }
            for (int s = 0; s < 4; s++)
            {
                for (int t= 0; t< 64; t++)
                {
                   Console.Write("{0} ", cd[s,t]);
                }
            } Console.WriteLine();

Console.WriteLine("3차원배열-----------------------------------");
            char[,,] cb = new char[2, 8, 16];
            int k = 0;
            for (int x = 0; x < 2; x++)
            {
                for (int y = 0; y < 8; y++)
                {
                    for (int z = 0; z < 16; z++)
                    {
                        k = 16 * 8 * x + 16 * y + z; cb[x, y, z] = (char)k;
                    }
                }
            } 
            for (int x = 0; x < 2; x++)
            {
                for (int y = 0; y < 8; y++)
                {
                    for (int z = 0; z < 16; z++)
                    {
                        Console.Write("{0} ", cb[x, y, z]);
                    }   Console.WriteLine();
                }
            } 
            Console.WriteLine("{0} {1} {2} {3}space", (char)48, (char)97, (char)65,(char)32);
Console.WriteLine("4차원배열-----------------------------------");
          
            char[, , ,] cc = new char[2, 8, 2, 8];

            for (int a = 0; a < 2; a++)
            {
                for (int b = 0; b < 8; b++)
                {
                    for (int c = 0; c < 2; c++)
                    {
                       for (int d = 0; d < 8; d++)
                    {
                        cc[a, b, c, d] = (char)(8 * 2 * 8 * a + 2 * 8 * b + 8 * c + d);
                    }
                    }
                }
            }
            for (int a = 0; a < 2; a++)
            {
                for (int b = 0; b < 8; b++)
                {
                    for (int c = 0; c < 2; c++)
                    {
                        for (int d = 0; d < 8; d++)
                        {
                            Console.Write("{0,3} ",cc[a, b, c,d]);
                        } Console.WriteLine();
                    }
                }
            }

'정리없는자료 > .NET' 카테고리의 다른 글

C# 스레드(thread)  (0) 2007/11/15
C# 윈도우 프로그래밍 예제파일  (0) 2007/11/14
C# Array for문 규칙  (0) 2007/11/13
C# string  (0) 2007/11/13
C# object  (0) 2007/11/06
C# interface  (0) 2007/11/06

top

Trackback Address :: http://deuxist.tistory.com/trackback/419 관련글 쓰기

Write a comment




namespace ObjectProgram
{
    class Program
    {
        int x = 1000;
        static void Main(string[] args)
        {
            int a = 100; int b = 100;
            if (a == b) Console.WriteLine("같다");
            else Console.WriteLine("다르다");
            Console.WriteLine("GetHashCode()::{0}", a.GetHashCode());
            Console.WriteLine("GetHashCode()::{0}", b.GetHashCode());
            Console.WriteLine("GetType()::{0}", a.GetType());
            Console.WriteLine("GetTypeCode()::{0}", a.GetTypeCode());
            Console.WriteLine("ToString()::{0}", a.ToString());
            Console.WriteLine(a.CompareTo(b)); //o
            Console.WriteLine(a.Equals(b));  //true
            if (a.Equals(b)) Console.WriteLine("같다");
            else Console.WriteLine("다르다");
            if (a.CompareTo(b) == 0) Console.WriteLine("같다");
            else Console.WriteLine("다르다");
            Program p = new Program();
            Console.WriteLine(p.x.ToString());
            object o1 = 100; object o2 = 100;
            Console.WriteLine(o1.GetHashCode());
            Console.WriteLine(o2.GetHashCode());
            if (o1 == o2) Console.WriteLine("같다");
            else Console.WriteLine("다르다"); //다르다
            if (o1.Equals(o2)) Console.WriteLine("같다"); // 값비교
            else Console.WriteLine("다르다"); //같다.
            Console.WriteLine(o1.GetType());
            Console.WriteLine(o2.GetType());
            string s1 = "한국";
            string s2 = "한국";
            
            Console.WriteLine(s1.GetHashCode()); //82086376
            Console.WriteLine(s2.GetHashCode()); //82086376
            if (s1 == s2) Console.WriteLine("같다");
            else Console.WriteLine("다르다"); //같다.
            if (s1.Equals(s2)) Console.WriteLine("같다");
            else Console.WriteLine("다르다"); //같다.
            Console.WriteLine(s1.GetType()); //System.string
            Console.WriteLine(s2.GetType()); //System.string
 }
         public override string ToString()
        {
            return base.ToString() +"이다";
        }
    }
}

'정리없는자료 > .NET' 카테고리의 다른 글

C# Array for문 규칙  (0) 2007/11/13
C# string  (0) 2007/11/13
C# object  (0) 2007/11/06
C# interface  (0) 2007/11/06
C# Override  (0) 2007/11/06
C# 상속예  (0) 2007/11/06

top
TAG c#, C#.NET, object

Trackback Address :: http://deuxist.tistory.com/trackback/417 관련글 쓰기

Write a comment



static void Main(string[] args)
        {
            InterfaceClass ic = new NewMiddleClass();
            ic.Name = "홍길동";
            Console.WriteLine(ic.MakeName());
        }
interface 예
interface InterfaceClass
    {
        string Name
        {
            get;
            set;
        }
        void MakeName(string name);
        string MakeName();
    }
    class NewMiddleClass : InterfaceClass
    {
        private string name = "홍";
        public string Name
        {
            get { return this.name; }
            set { this.name = value; }
        }
        public void MakeName(string name)
        {
            this.name = name;
        }
        public string MakeName()
        {
            return this.name + "님";
        }

'정리없는자료 > .NET' 카테고리의 다른 글

C# string  (0) 2007/11/13
C# object  (0) 2007/11/06
C# interface  (0) 2007/11/06
C# Override  (0) 2007/11/06
C# 상속예  (0) 2007/11/06
C# 네임스페이스(namespace)  (0) 2007/11/05

top

Trackback Address :: http://deuxist.tistory.com/trackback/416 관련글 쓰기

Write a comment



변수관계가 아닌 함수관계이다.

 class Program
    {
        static void Main(string[] args)
        {
            Student st = new Student();
            st.MakeName("홍길동"); st.MakeAddress("구로구");
            Console.WriteLine(st.MakeName());
            Console.WriteLine(st.MakeAddress());
           
            MiddleClass mt = new MiddleClass();
            mt.MakeName("홍길동"); mt.MakeAddress("구로구");
            Console.WriteLine(mt.MakeName());
            Console.WriteLine(mt.MakeAddress());
           
            st = mt;
            Console.WriteLine(st.MakeName()); //중요 // mt = st; 성립안됨--> override
            Console.WriteLine(st.MakeAddress());+
           
        }
    }
    class Student
    {
        protected string name = string.Empty;
        protected string address = string.Empty;
        public string MakeName()
        {
            return this.name;
        }
        public void MakeName(string name)
        {
            this.name = name;
        }
        public string MakeAddress()
        {
            return this.address;
        }
        public void MakeAddress(string address)
        {
            this.address = address;
        }

    }
    class MiddleClass : Student
    {
        public override string MakeName()
        {
            return this.name + "님";
        }
      
        public override string MakeAddress()
        {
            return this.address + "지역";
        }
       

    }

'정리없는자료 > .NET' 카테고리의 다른 글

C# object  (0) 2007/11/06
C# interface  (0) 2007/11/06
C# Override  (0) 2007/11/06
C# 상속예  (0) 2007/11/06
C# 네임스페이스(namespace)  (0) 2007/11/05
C# 구조체(structure), 열거형(enumeration)  (2) 2007/11/05

top

Trackback Address :: http://deuxist.tistory.com/trackback/415 관련글 쓰기

Write a comment



structure는 class의 사용법과 같으며 메모리의 사용만 다르다.(stack 사용)
structure
Program3 p3 = new Program3();
p3.X = 10000; Console.WriteLine(p3.X);
p3.Y = 10000; Console.WriteLine(p3.Y);
struct Program3
    {
        int x;  int y;
        public int X
        {
            get { return this.x; }
            set { this.x = value; }
        }
        public int Y
        {
            get { return this.y; }
            set { this.y = value; }
        }
    }

enumeration
enum WeekDay { mon, tue, wed, thu, fri, sat, sun }; //mo = 0, tue =1...

        static void Main(string[] args)
        {
            WeekDay wd = WeekDay.mon;
            Console.WriteLine(wd);
            Console.WriteLine((int)wd);
     
  }

'정리없는자료 > .NET' 카테고리의 다른 글

C# 상속예  (0) 2007/11/06
C# 네임스페이스(namespace)  (0) 2007/11/05
C# 구조체(structure), 열거형(enumeration)  (2) 2007/11/05
C# property  (0) 2007/11/05
C# 재귀호출(recursive function call)-Factorial  (0) 2007/11/05
C# for(), foreach(), params  (0) 2007/11/05

top

Trackback Address :: http://deuxist.tistory.com/trackback/412 관련글 쓰기

  1. 나그네 2008/11/09 21:20 댓글주소 | 수정/삭제 | 댓글

    오홋! 프로퍼티도 넣을 수 있었나?

    -- 추가 내용 --
    확인결과
    변수(기본), 메서드, 프로퍼티, 델리게이트, 이벤트, 생성자(클래스의 생성자와는 좀 다름) 모두 사용가능했음.
    다만 NotInheritable로 되어있어 상속하는것 과 함께 성속받는게 안될뿐.. 물론 메모리 사용도 좀 다르지만..

    -- 추가 내용2 --
    구조체내에서 인덱서는 선언은 가능하나. 사용은 불가능하네요.(사용할려하면 에러 뜲)

Write a comment



속성(property)은 Basic의 영향을 받아 C#언어에서 새로 추가된 기능으로, 필드와 마찬가지로 특성을 구현하는데 사용.
예전방식
class Program
    {
        static void Main(string[] args)
        {
            Program2 p2 = new Program2();
            p2.SetX(3); p2.SetY(4);
            Console.WriteLine(p2.MakeX());
            Console.WriteLine(p2.MakeY());
        }

    }
    class Program2
    {
        private int x; private int y;
        public int MakeX()
        { return this.x;}
        public int MakeY()
        { return this.y;}
        public void SetX(int x)
        { this.x = x;}
        public void SetY(int y)
        { this.y = y;}
    }

property
class Program
{
  static void Main(string[] args)
        {
            p2.X = 100; Console.WriteLine(p2.X);
            p2.Y = 100; Console.WriteLine(p2.Y);
        }
    }
    class Program2
    {
        private int x; private int y; //field 필드
        public int X
        {
            get { return this.x; }
            set { this.x = value; }
        }
        public int Y
        {
            get { return this.y; }
            set { this.y = value; }
        }


'정리없는자료 > .NET' 카테고리의 다른 글

C# 네임스페이스(namespace)  (0) 2007/11/05
C# 구조체(structure), 열거형(enumeration)  (2) 2007/11/05
C# property  (0) 2007/11/05
C# 재귀호출(recursive function call)-Factorial  (0) 2007/11/05
C# for(), foreach(), params  (0) 2007/11/05
C# ref, out  (0) 2007/11/05

top

Trackback Address :: http://deuxist.tistory.com/trackback/411 관련글 쓰기

Write a comment



static void Main(string[] args)
      {
            int temp = 0;
            for(int i = 0; i <= 5; i++)
            {
            int newsum = 0;
            newsum = FacSum(i);
            Console.WriteLine(newsum);
            temp += newsum;
            Console.Write("{0} ", newsum);
            }
            Console.Write("\n");
            Console.Write("{0} ", temp);
            Console.Write(FacSum(5,false));
        }
        //재귀호출(recursive function call)
        public static int FacSum(int no)
        {
            if (no == 0) return 0;
            else return no + FacSum(no - 1);
        }

        public static int FacSum(int no, bool b)
        {
            int temp = 0;
            for (int i = 0; i <= no; i++)
            {
                temp += i;
            }
            Console.Write("{0} ", temp);
            if (no == 0) return 0;
            else return temp + FacSum(no - 1, false);
        }

'정리없는자료 > .NET' 카테고리의 다른 글

C# 구조체(structure), 열거형(enumeration)  (2) 2007/11/05
C# property  (0) 2007/11/05
C# 재귀호출(recursive function call)-Factorial  (0) 2007/11/05
C# for(), foreach(), params  (0) 2007/11/05
C# ref, out  (0) 2007/11/05
C# 클래스 기초  (0) 2007/11/05

top

Trackback Address :: http://deuxist.tistory.com/trackback/410 관련글 쓰기

Write a comment



비교--
            char[] ca = new char[3] { 'a', 'b', 'c' };

            for (int i = 0; i < ca.Length; i++)
            {
                Console.Write("{0} ", ca[i]);
            }

            Console.Write("\n");
          foreach (char c in ca)
            {
                Console.Write("{0} ", c);
            }

--------------------------------------------------------------------------
인수가 가변적

            Program.NewSum(1,2);
           Program.NewSum(1,2,3);
            Program.NewSum(1,2,3,4);
       public static void NewSum(params int[] ia)
       {
           foreach (int i in ia)
           {
               Console.Write("{0} ", i);
           }
           Console.Write("\n");
       }

 

'정리없는자료 > .NET' 카테고리의 다른 글

C# property  (0) 2007/11/05
C# 재귀호출(recursive function call)-Factorial  (0) 2007/11/05
C# for(), foreach(), params  (0) 2007/11/05
C# ref, out  (0) 2007/11/05
C# 클래스 기초  (0) 2007/11/05
C# 2차원배열 실습  (0) 2007/11/02

top

Trackback Address :: http://deuxist.tistory.com/trackback/409 관련글 쓰기

Write a comment



//ref
class Program
    {
        static void Main(string[] args)
        {
            int newx = 100;
           Console.WriteLine("newx{0} ",newx);
           Program.Sum(ref newx, false);
           Console.WriteLine(newx);
       }
       static void Sum(ref int x, bool b)
       {
           x = x + 1000;
           Console.WriteLine(x);
       }
 -------------------------------------------------------
class Program
    {
        static void Main(string[] args)
        {
            int newx = 100;
            Console.WriteLine("newx{0} ",newx);
            Program.Sum(ref newx, false);
            Console.WriteLine(newx);
        }
        static void Sum(ref int x, bool b)
        {
            x = x + 1000;
            Console.WriteLine(x);
        }
---------------------------------------------------------
//out
class Program
    {
        static void Main(string[] args)
        {
            int newx = 100;
            Console.WriteLine("newx{0} ",newx);
            Program.Sum(out newx, false);
            Console.WriteLine(newx);
        }
        static void Sum(out int x, bool b)
        {
            x = 0;
            x = x + 1000;
            Console.WriteLine(x);
        }

'정리없는자료 > .NET' 카테고리의 다른 글

C# 재귀호출(recursive function call)-Factorial  (0) 2007/11/05
C# for(), foreach(), params  (0) 2007/11/05
C# ref, out  (0) 2007/11/05
C# 클래스 기초  (0) 2007/11/05
C# 2차원배열 실습  (0) 2007/11/02
C# 불규칙 배열 regged array  (0) 2007/11/02

top
TAG c#, C#.NET, out, Ref

Trackback Address :: http://deuxist.tistory.com/trackback/408 관련글 쓰기

Write a comment



using System;
using System.Collections.Generic;
using System.Text;

namespace Method
{
    class Program
    {
        static void Main(string[] args)
        {
            int x = 1000;
            string y = "한국";
            Console.WriteLine("{0,5} {1,4}", x, y);
            Console.WriteLine("{0,-5} {1,-4}", x, y);
            Sum(x, 5);
            int result = Program.Sum(x,5,false);
            Console.WriteLine(result);
            Program p = new Program();
            p.Differ(x, 5);
            Console.WriteLine("x1 = {0}",x);
            Program.Sum(ref x);
            Console.WriteLine("x3 = {0}",x);
            int[] ia = new int[2] { 100, 200 };
            Program.Sum(ia);
            for (int i = 0; i < ia.Length; i++)
            {
                Console.WriteLine("::::::::::::::{0}",ia[i]);
            }
        }
        static void Sum(int[] newia) // 배열형식은항상ref가붙어있음(string (X))
        {
            int tempsum= 0;
            int no = newia.Length;
            for(int i = 0;i < no; i++)
            {
                tempsum += newia[i];
                newia[i] = newia[i] + 100;
            }
            Console.WriteLine("합계{0}",tempsum);
            for (int i = 0; i < no; i++)
            {
                Console.WriteLine("------------{0}",newia[i]);
            }
        }

        static void Sum(ref int x)
        {
            x = x + 100;
            Console.WriteLine(x);
        }
        static void Sum(int x, int y) //function define
        {
            Console.WriteLine(x + y);
        }
        static int Sum(int x, int y, bool b) //function define
        {
            return x + y;
        }
        void Differ(int x, int y) //function define
        {
            Console.WriteLine(x - y);
        }
    }
}

'정리없는자료 > .NET' 카테고리의 다른 글

C# for(), foreach(), params  (0) 2007/11/05
C# ref, out  (0) 2007/11/05
C# 클래스 기초  (0) 2007/11/05
C# 2차원배열 실습  (0) 2007/11/02
C# 불규칙 배열 regged array  (0) 2007/11/02
C# conditional statement 조건문(if,switch)  (0) 2007/11/01

top

Trackback Address :: http://deuxist.tistory.com/trackback/407 관련글 쓰기

Write a comment



이름과 국어 영어점수를 입력받아 총점을 출력          

            string[] name = new string[3]; //이름저장
            string[] subject = new string[2] { "kor", "eng" };
            int[,] score = new int[3,2];
            Console.WriteLine("학생 3명의 이름 국어점수 영어점수 입력");
            for (int ii = 0; ii < name.Length; ii++)
            {
                Console.Write("학생이름:");
                name[ii] = Console.ReadLine();
                for (int jj = 0; jj < subject.Length; jj++)
                {
                    Console.Write("{0}:",subject[jj]);
                    score[ii,jj] = Convert.ToInt32(Console.ReadLine());
                }
                Console.Write("\n");
            }
            Console.WriteLine("** 학생 국어 영어 총점 **");
            for (int k = 0; k < name.Length; k++)
            {
                Console.WriteLine("{0,5} {1,5} {2,5} {3,5}", name[k], score[k, 0], score[k, 1], score[k, 0] + score[k, 1]);
            }

'정리없는자료 > .NET' 카테고리의 다른 글

C# ref, out  (0) 2007/11/05
C# 클래스 기초  (0) 2007/11/05
C# 2차원배열 실습  (0) 2007/11/02
C# 불규칙 배열 regged array  (0) 2007/11/02
C# conditional statement 조건문(if,switch)  (0) 2007/11/01
C# value type  (0) 2007/11/01

top

Trackback Address :: http://deuxist.tistory.com/trackback/405 관련글 쓰기

Write a comment



불규칙 배열 regged array

            int[][] ia = new int[3][];
            ia[0] = new int[3];
            ia[1] = new int[2];
            ia[2] = new int[1];
            /*
            for (int i = 0; i < ia.GetLength(0); i++)
            {
                for (int j = 0; j < ia[i].GetLength(0); j++)
                {
                    Console.Write("{0} ",ia[i][j]);
                }
                Console.Write("\n");
            }
            */

            for (int i = ia.GetLength(0)-1; i >= 0; i--)
            {
                int temp = 3 - ia[i].GetLength(0);
                //Console.Write(temp);
                for (int j = 0; j < temp; j++)
                {
                    Console.Write(" ");
                }
                for (int j = 0; j < ia[i].GetLength(0); j++)
                {
                    Console.Write("{0} ", ia[i][j]);
                }
                Console.Write("\n");
            }
            int[,] ib = new int[2, 3];
            int [][] ic = new int[2][];
            ic[0] = new int[3]; ic[1] = new int[3];
            ////////////////////////////////////////////////
            for (int i = 0; i < ib.GetLength(0); i++)
            {
                for (int j = 0; j < ib.GetLength(1); j++)
                {
                    ib[i,j] = (i) * 3 + j+1;
                }
            }
            ib.SetValue(100, 0, 0);
            for (int i = 0; i < ib.GetLength(0); i++)
            {
                for (int j = 0; j < ib.GetLength(1); j++)
                {
                    Console.WriteLine("{0} ", ib[i, j]);
                }
                Console.WriteLine();
            }
            ////////////////////////////////////////////////
            //
            for (int i = 0; i < ic.GetLength(0); i++)
            {
                for (int j = 0; j < ic[i].GetLength(0); j++)
                {
                    ic[i][j] = (i) * 3 + j + 1;
                }
            }
            //ic.SetValue(100, 0, 0);
            ic[0][0] = 100;
            for (int i = 0; i < ic.GetLength(0); i++)
            {
                for (int j = 0; j < ic.GetLength(0); j++)
                {
                    Console.Write("{0} ", ic[i][j]);
                }
                Console.WriteLine();
            }
        }

    }
}

'정리없는자료 > .NET' 카테고리의 다른 글

C# 클래스 기초  (0) 2007/11/05
C# 2차원배열 실습  (0) 2007/11/02
C# 불규칙 배열 regged array  (0) 2007/11/02
C# conditional statement 조건문(if,switch)  (0) 2007/11/01
C# value type  (0) 2007/11/01
C# Operator 연산자  (0) 2007/11/01

top

Trackback Address :: http://deuxist.tistory.com/trackback/404 관련글 쓰기

Write a comment



연산자란 피연산자에 어떤 특정한 기능을 수행하도록 정의된 기호라고 정의될 수 있다.
class Program
    {
        static void Main(string[] args)
        {
            int xx = 1000;
            int yy = 2000;
           
            int temp = xx + yy;
            Console.WriteLine(temp.ToString());
            temp = xx - yy; Console.WriteLine(temp.ToString());
            temp = xx * yy; Console.WriteLine(temp.ToString());
            temp = xx / yy; Console.WriteLine(temp.ToString());
            temp = xx % yy; Console.WriteLine(temp.ToString());

            float f1 = 4.2f; float f2 = 3.0f;
            float ftemp = f1 / f2; Console.WriteLine(ftemp.ToString());
            ftemp = f1 % f2;
            Console.WriteLine(ftemp.ToString());
            ftemp = -ftemp;
            Console.WriteLine(ftemp.ToString());

            bool b = true;
            Console.WriteLine(b.ToString());
            b = (10 == 5); Console.WriteLine(b);
            b = (10 != 5); Console.WriteLine(b);
            b = (10 >= 5); Console.WriteLine(b);
            b = (10 <= 5); Console.WriteLine(b);
            
            int e = 13, f=7, g=0;
            Console.WriteLine("{0} {1} {2}", e, f, g);
            g = e & f; Console.WriteLine(g); //5
            g = e | f; Console.WriteLine(g); //15
            g = e ^ f; Console.WriteLine(g); //10
            /* 13 : 0000101 7 : 00000111 & : 00000101 | : 00001111 ^ : 00001010 */
            bool c;
            c = (10 > 5) && (5 == 5); Console.WriteLine(c);
            c = (10 < 5) || (5 == 5); Console.WriteLine(c);
            c = !(10 > 5); Console.WriteLine(c);
                      int h = 100; h = h + 1; Console.WriteLine(h);
           ++h; Console.WriteLine(h);
           h++; Console.WriteLine(h);

           int no = 0; no = ++h; Console.WriteLine(h);
           no = h++; Console.WriteLine("++"+h);

           string str = "대한" + "민국"; //(X)
           Console.WriteLine(str);
           str = string.Concat("kor", "ea"); //(O) / +연산자가 string.Concat실행 /
           Console.WriteLine(str);
           
           int i = 7;
           i >>= 2; Console.WriteLine(i);
           i <<= 2; Console.WriteLine(i);
           i -= 2; Console.WriteLine(i); // i = i - 2;
           i |= 2; Console.WriteLine(i); // I = I | 2;

           int j = 13;
           j = ~j;  // -14
           Console.WriteLine(j)

        }
    }
}

'정리없는자료 > .NET' 카테고리의 다른 글

C# conditional statement 조건문(if,switch)  (0) 2007/11/01
C# value type  (0) 2007/11/01
C# Operator 연산자  (0) 2007/11/01
C# Array  (0) 2007/10/31
C# FormatString  (0) 2007/10/31
C# datatype convertion 형변환  (0) 2007/10/31

top

Trackback Address :: http://deuxist.tistory.com/trackback/400 관련글 쓰기

Write a comment



namespace FormatString
{
    class Program
    {
        static void Main(string[] args)
        {
            int num = 1234567;
            Console.WriteLine("{0}", num);
            Console.WriteLine("{0:g}", num);
            Console.WriteLine("{0:G}", num);
            Console.WriteLine("{0:D}", num);
            Console.WriteLine("{0:D9}", num);
            string str = "대한민국";
            Console.WriteLine(str);
            str = string.Format("{0:D9이다}", 100);
            Console.WriteLine(str);
            Console.WriteLine(String.Format("{0:D9}", num));
            Console.WriteLine("{0:c}", num);
            Console.WriteLine("{0:C}", num);
            Console.WriteLine("{0:e}", num);
            Console.WriteLine("{0:E}", num);
            Console.WriteLine("{0:f}", num);
            Console.WriteLine("{0:F}", num);
            Console.WriteLine("{0:n}", num);
            Console.WriteLine("{0:N}", num);
            Console.WriteLine("{0:p}", num);
            Console.WriteLine("{0:P}", num);
            Console.WriteLine("{0:x}", num);
            Console.WriteLine("{0:X}", num);
           
            //
            Console.WriteLine("{0:00.000}", 1.5);
            Console.WriteLine("{0:(00.00)}", num);
            //babo:: string str2 = "(" + Convert.ToString(100) + ")";
            string str2 = string.Format("{0:(000:00)}", 100);
            Console.WriteLine(str2);
            Console.WriteLine("{0:(###.##)}", num);
            Console.WriteLine("{0:(0,000.##)}", num);
            Console.WriteLine("{0:(0,000.0)}", num);
            Console.WriteLine("{0:(###.##%)}", num);
            Console.WriteLine("{0:(00e+000)}", num);
            Console.WriteLine("{0:('정수부분'###.##'소수부분')}", num);
           
            decimal phone = 01190039649;
            string phonestr = string.Format("{0:000-####-####}", phone);
            Console.WriteLine("{0:000-####-####}", phone);
            Console.WriteLine(phonestr);
        }
    }
}

'정리없는자료 > .NET' 카테고리의 다른 글

C# Operator 연산자  (0) 2007/11/01
C# Array  (0) 2007/10/31
C# FormatString  (0) 2007/10/31
C# datatype convertion 형변환  (0) 2007/10/31
C# constant & read-only variable  (0) 2007/10/31
[.NET] 시작  (0) 2007/08/14

top

Trackback Address :: http://deuxist.tistory.com/trackback/398 관련글 쓰기

Write a comment



namespace ConstVariable
{
    class Program
    {
        int i = 10000;
        int j = 20000;

        static void Main(string[] args)
        {
            int k = 100; //4byte
            short l = 100; //2byte -32768 ~ + 32767
            Console.WriteLine("k = {0}, l = {1}", k, l);
            /////////////////////////////////////////////////////////
            int q = 32768;
            short w = 32767;
            q = w; //4byte variabble 2byte value allocation
            q = (int)w;
            Console.WriteLine("q = {0}, w = {1}", q, w);
            q = 32768;
            w = 32767;
            w = (short)q; //2byte 변수 4byte 값
            Console.WriteLine("q = {0}, w = {1}", q, w);
            // 32768 -32768
            // Bin : 01111111 11111111 + 1 = 10000000 00000000
            q = Convert.ToInt32(w);
            Console.WriteLine(q.ToString());
            q = Convert.ToInt32("32768");
            Console.WriteLine(w.ToString());
            float ff = 10.0f;
            double dd = 20.0;
            Console.WriteLine("{0} {1}", ff, dd);
            Console.WriteLine("{0:f} {1:f}", ff, dd); //실수 출력
            Console.WriteLine("{0:g} {1:g}", ff, dd); //일반 출력
            Console.WriteLine("{0:c} {1:d} {2:e}", 10, 10, 10);
            Console.WriteLine("{0:n} {1:r}", -1000.450, -1000.450);
            Console.WriteLine("{0:x} {1:p}", 11, 10.5);
            ff = (float)dd;
            Console.WriteLine("{0:f}", ff);
         }
    }
}

'정리없는자료 > .NET' 카테고리의 다른 글

C# Operator 연산자  (0) 2007/11/01
C# Array  (0) 2007/10/31
C# FormatString  (0) 2007/10/31
C# datatype convertion 형변환  (0) 2007/10/31
C# constant & read-only variable  (0) 2007/10/31
[.NET] 시작  (0) 2007/08/14

top

Trackback Address :: http://deuxist.tistory.com/trackback/397 관련글 쓰기

Write a comment



const 란 키워드는 변수를 상수화하겠다는 것을 의미하며, 반드시 초기화 시켜야 한다.

namespace ConstVariable
{
    class Program
    {
        int i = 10000;
        int j = 20000;

        static void Main(string[] args)
        {
            const int i = 100;
            int j = 200;
            System.Console.WriteLine(i.ToString());
            Console.WriteLine(j.ToString());
            j = 300;
            Console.WriteLine(j.ToString());
            // i = 300; const 재할당은 허용하지않음

            Program pr = new Program(); //클래스 객체변수 사용
            Console.WriteLine(pr.i.ToString());
            Console.WriteLine(pr.j.ToString());
            Console.WriteLine("{0} 과 {1}", i, j);
        }
    }
}

'정리없는자료 > .NET' 카테고리의 다른 글

C# Operator 연산자  (0) 2007/11/01
C# Array  (0) 2007/10/31
C# FormatString  (0) 2007/10/31
C# datatype convertion 형변환  (0) 2007/10/31
C# constant & read-only variable  (0) 2007/10/31
[.NET] 시작  (0) 2007/08/14

top
TAG c#, C#.NET, const

Trackback Address :: http://deuxist.tistory.com/trackback/396 관련글 쓰기

Write a comment