2011-10-06 4 views
0

데이터 격자보기가 있는데 특정 열 값이 포함 된 특정 행만 강조 표시 할 수 있는지 궁금합니다.DataGridView (DGV)의 다른 색칠 된 선

그래서 모든 행 FUJI/UNIVERSAL 같다 지정된 열이있는 행을 제외하고 흰색 텍스트와 검은 색에 기본값으로 설정하고 싶습니다. 이 줄에는 검은 색 텍스트가 노란색으로 표시됩니다.

제 질문은 .. 가능합니까? 그렇다면 어떻게?

답변

2

가장 좋은 장소는 DataGridView의 RowPrePaint 이벤트입니다.

다음은이를 수행하는 방법입니다.

void dataGridView1_RowPrePaint(object sender, 
     DataGridViewRowPrePaintEventArgs e) 
{ 
    if (dataGridView1.Rows[e.RowIndex].Cells[0].Value == "YourConditionalValue") 
    { 
     dataGridView1.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.Yellow; 
    } 
} 
+0

가장 단순하고 짧은 코드. 감사! – theNoobGuy

1

DataGridView 컨트롤에 대한 OnPaint 이벤트를 처리하십시오.

행을 구문 분석하고 찾고있는 정보가있는 행의 색을 설정하십시오.

일부 예제 코드 :

int specificColumnIndex = 5; 
const string FUJIUNIV = "FUJI/UNIVERSAL"; 
const Color cFUJIBACK = Color.Yellow; 
const Color cFUJITEXT = Color.Black; 

public Form1() { 
    InitializeComponent(); 
    dataGridView1.Paint += new PaintEventHandler(DataGridView_Paint); 
} 

private void DataGridView_Paint(object sender, PaintEventArgs e) { 
    foreach (DataGridViewRow row in dataGridView1.Rows) { 
    if (row.Cells[specificColumnIndex].Value.ToString() == FUJIUNIV) { 
     foreach (DataGridViewCell cell in row.Cells) { 
     cell.Style.BackColor = cFUJIBACK; 
     cell.Style.ForeColor = cFUJITEXT; 
     cell.Style.SelectionBackColor = Color.Gold; 
     } 
    } 
    } 
} 

} 예를 들어

1

OnCellFormatting 이벤트를 처리하여.

다음은 이전 WinForms 취미 프로젝트의 실제 코드입니다. 정확하게 수행됩니다. 그것은 또한 논평하는 것이 얼마나 중요한지 다시 나에게 가르친다 (나는 지금까지 그것을 아직도 기억할 기회가 없다).

나는 그것을 당신의 목적에 맞출 수있을 것이라고 확신합니다.

private void sheetCalendar_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e) 
    { 
     if (CurrentRota == null) 
     { 
      return; 
     } 
     /* A word of explanation is needed. We retrieve the DataGridView from sender 
     * and we access the cell in question directly. 
     * MSDN advices against it - 
     * "to avoid performance penalties When handling this event, 
     * access the cell through the parameters of the event handler 
     * rather than accessing the cell directly." 
     * 
     * The problem is that we don't want to set the same colour to the same cell 
     * over and over again. 
     * And e.CellStyle always "forgets" what colour the call had had! */ 
     var dgrid = sender as DataGridView; 
     var _col = e.ColumnIndex; 
     var _row = e.RowIndex; 
     var _highlight = (((Rota) sheetCalendar.Rows[e.RowIndex].DataBoundItem).Monday == 
          CurrentRota.Monday); 
     var color = _highlight ? 
            Settings.Default.DGRIDCalendar_CurrentlyEditedBackColor : 
                           SystemColors.Window; 
     if (dgrid[_col, _row].Style.BackColor != color) 
      dgrid[_col, _row].Style.BackColor = color; 

    }