2012-05-09 3 views
1

DataGridView에서 10 명의 전체 사과를 30 명으로 나누고 싶습니다.
DataGridView는 KeyPreview가 true로 설정된 양식에 있습니다. 사람들의 이름은 readonly로 설정된 DataGridViewTextBoxColumn (Column1)에 표시됩니다. 정수는 빈 DataGridViewTextBoxColumn (Column2)에 입력됩니다. 키를 놓으면 합계가 계산/재 계산되고 column2의 합계가 30이면 양식 확인 버튼이 활성화됩니다 (이 비활성화 된 경우).KeyPress 이벤트 블록 DataGridView의 KeyUp 이벤트

문제는 keyEvents와 관련됩니다. KeyPress 이벤트를 바인드하면 KeyUp이 트리거되지 않습니다.

// Bind events to DataGridViewCell 
    private void m_DataGridView_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e) 
    { 
     if (e.Control != null) 
     { 
      e.Control.KeyUp -= m_DataGridView_KeyUp; 
      e.Control.KeyPress -= m_DataGridView_KeyPress; 
      e.Control.KeyUp += m_DataGridView_KeyUp; 
      e.Control.KeyPress += m_DataGridView_KeyPress; 
     } 
    } 

    //Only accept numbers 
    private void m_GridView_KeyPress(object sender, KeyPressEventArgs e) 
    { 
     if ((e.KeyChar >= 48 && e.KeyChar <= 57) || e.KeyChar == 8) 
     { 
      e.Handled = false; 
     } 
     else 
     { 
      e.Handled = true; 
     } 
    } 

    // Sum the apples in column2 
    private void m_DataGridView_KeyUp(object sender, DataGridViewCellEventArgs e) 
    { 
     if (e.ColumnIndex == 1 && e.RowIndex > 0) 
     { 
      int count = 0; 
      int parser = 0; 

      foreach (DataGridViewRow item in this.m_DataGridView.Rows) 
      { 
       if (item.Cells[1].Value != null) 
       { 
        int.TryParse(item.Cells[1].Value.ToString(), out parser); 
        count += parser; 
       } 
      } 

      //make the ok button enabled 
      m_buttonDividedApplen.Enabled = (count == 30); 
     } 
    } 

이 이야기의 문제는 낯선 사람과 낯선 사람이됩니다. 셀을 전환하면 keyup 이벤트가 트리거됩니다. 때로는 키 입력이 한 번 트리거됩니다.

+0

KeyUp이 항상 실행 중이 아니며 키 누르기로 처리했을 때만 실행됩니까? – gbianchi

+0

KeyUp은 KeyPress가 첨부되지 않은 경우에만 실행됩니다. –

답변

0

편집 컨트롤이 작동하지 않을 때마다 동일한 이벤트에 핸들러를 다시 부착합니다. 이는 결코 바뀌지 않습니다.

코드를 단계별로 실행하면 KeyPress 이벤트가 셀을 편집 한 횟수와 직접적으로 관련이 있음을 알 수 있습니다. 다시 부착 한 후

e.Control.KeyUp -= m_DataGridView_KeyUp; 
    e.Control.KeyPress -= m_DataGridView_KeyPress; 

을 : 먼저 핸들러를 제거하십시오

e.Control.KeyUp += m_DataGridView_KeyUp; 
    e.Control.KeyPress += m_DataGridView_KeyPress; 

을 keyUp 등 화재되는지 확인합니다.

+0

글쎄, 나는 그것을 또한 시도했다. 결과는 정확히 같습니다. 핸들러를 다시 연결해도 결과가 변경되지는 않습니다. –

+0

아, 미안하지만 그게 도움이되지 못했습니다. 하지만 KeyPress 이벤트가 실수로 여러 번 실행되므로 핸들러를 연속해서 다시 연결하지 않아야합니다. –

+0

또한 주요 양식의 KeyPreview를 사용하도록 설정 한 이유가 확실하지 않습니다. 디자인 타임에 핸들러를 DataGrid에 연결하고 폼 수준에서 키 누르기 이벤트를 처리하지 않는 것이 좋을까요? –

관련 문제