Sduty/C#

DataGridView control I

돌멘 2020. 2. 22. 13:00

    // 1. 홀수행을 다른 색으로 보여주고 싶을 때
    dbView.AlternatingRowsDefaultCellStyle.BackColor = Color.Aqua;

    // 2. 여러개의 셀이나 행을 선택하지 못하도록 막고 싶을 때
    dbView.MultiSelect = false;

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

    dbView.SelectionMode = DataGridViewSelectionMode.FullRowSelect; 


    // 4. 특정 행이나 열을 고정시키고 스크롤하지 못하도록 막고 싶을 때
    dbView.Columns[1].Frozen = true;
    dbView.Columns[1].DividerWidth = 3;

    // 5. 헤더열이나 헤더행의 색을 변경하고 싶을 때
    // Visual 사용하지 않을 때
    dbView.EnableHeadersVisualStyles = false;
    dbView.ColumnHeadersDefaultCellStyle.BackColor = Color.RosyBrown;
    dbView.RowHeadersDefaultCellStyle.BackColor = Color.SeaGreen;
    // 열과 행의 경계선 스타일 지정
    dbView.RowHeadersBorderStyle = DataGridViewHeaderBorderStyle.Single;
    dbView.ColumnHeadersBorderStyle = DataGridViewHeaderBorderStyle.Single;

    // 6. 열에 보여지는 문자열을 여러행으로 보여주고 싶을 때
    dbView.DefaultCellStyle.WrapMode = DataGridViewTriState.True;
    dbView.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCells;

    // 7. 맨 밑까지 스크롤하고 싶을 때
    dbView.FirstDisplayedScrollingRowIndex = dbView.Rows.Count - 1;

    // 8. 열안에 문자열 선택하고 싶을 때
    // 폼_Load이벤트핸들러가 BeginEdit를 호출할 경우 폼을 먼저 표시할 필요가 있음
    this.Show();
    // 2행 1열 열을 현재 열로 지정
    dbView.CurrentCell = dbView[01];
    // 현재 열을 편집상태로
    dbView.BeginEdit(true);

    // 9. 왼쪽 윗 빈 열에 값 설정하고 싶을 때
    dbView.TopLeftHeaderCell.Value = "매장";

    // 10. 열 순서를 마음대로 바꾸고 싶을 때
    dbView.AllowUserToOrderColumns = true;

    //11. 행번호 보여주고 싶을 때

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


    // 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);
}

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

//13. 특정값을 가진 열을 좀 다르게 보여주고 싶을 때
private void dbView_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
    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;
            }
        }
    }
}

// 14. 선택한 행이나 열에 대한 값을 확인하고 싶을 때
    /*
     * 현재 선택된 셀 SelectedCells
     *  foreach(DataGridViewCell cell in dgv.SelectedCells) {}
     * 현재 선택된 셀수 SelectedCells.Count
     *  for(int i=0; i<dgv.SelectedCells.Count; i++) {}
     * 현재 선택된 행 SelectedRows
     *  foreach(DataGridViewRow row in dgv.SelectedRow) {}
     * 특정 셀이 선택된건지 아닌지 체크 dgv[x,y].Selected
     * 특정 행이 선택된건지 아닌지 체크 dgv.Rows[n].Selected
     * (x,y)위치에 있는 셀 선택상태 dgv[x,y].Selected = true;
     * n행 선택상태 dgb.Rows[n].Selected = true;
     * 선택된 상태 제거 ClearSelection
     */


// 15. 오토컴플릿 기능을 사용하고 싶을 때
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;
    }
}

// 16. 오른쪽버튼 클릭시 열 선택을 할 수 있도록 하고 싶을 때
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; // 선택상태 반전
        }
    }
}

// 17. 행 삭제시 확인메세지를 보여주고 싶을 때
private void dbView_UserDeletingRow(object sender, DataGridViewRowCancelEventArgs e)
{
    if (MessageBox.Show("삭제하시겠습니까?""지정한 행삭제", MessageBoxButtons.YesNo) == DialogResult.No)
    {
        e.Cancel = true//삭제 취소
    }


출처: http://blog.naver.com/atssa60/20102158316


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

DataGrid control III(Excel로 변환)  (0) 2020.02.22
DataGridView control II  (0) 2020.02.22
문자열 split(ASP.NET 에도 해당됨)  (0) 2018.05.04
C#배포시 오라클client 설치없이 배포  (0) 2017.09.15
DataTable 중복  (0) 2014.03.06