2014-07-25 2 views
1

Windows Forms 응용 프로그램에서 datagridview에 문제가 있습니다. AllowUserToAddRows = true를 설정 했으므로 마지막 빈 행을 두 번 클릭하면 선택한 셀이 편집 모드로 전환되고 사용자가 textboxcolumn에 무언가를 쓸 때 새 행이 추가됩니다.DataGridView에서 DefaultValuesNeeded를 사용할 때 새 행을 추가 할 수 없습니다.

이것은 모두 괜찮습니다.하지만 사용자가 새 행을 편집 (두 번 클릭)하면 모든 필드가 첫 번째 행의 값을 사용하여 기본값으로 채워지므로 내 DataGridview에서 DefaultValuesNeeded 이벤트를 설정합니다. 그리고 코드 뒤에서는 선택된 행의 모든 ​​필드를 채 웁니다.

문제는 DefaultValuesNeeded가 실행 된 후에 하단에 새로운 행이 나타나지 않는다는 것입니다.

이 문제를 어떻게 해결할 수 있습니까?

+0

DataGridView에 바인딩 소스가 있습니까? – Moop

답변

0

DataGridView에 바인딩 소스가있는 경우 DefaultValuesNeeeded 이벤트 처리기에서 EndCurrentEdit()을 호출하여 기본값을 사용하여 새 행을 즉시 커밋 할 수 있습니다. 당신이 바인딩 소스가없는 경우

{ 
     dt = new DataTable(); 
     dt.Columns.Add("Cat"); 
     dt.Columns.Add("Dog"); 

     dataGridView1.AllowUserToAddRows = true; 
     dataGridView1.DefaultValuesNeeded += dataGridView1_DefaultValuesNeeded; 

     dataGridView1.DataSource = dt;   
    } 

    void dataGridView1_DefaultValuesNeeded(object sender, DataGridViewRowEventArgs e) 
    { 
     var dgv = sender as DataGridView; 
     if(dgv == null) 
      return; 

     e.Row.Cells["Cat"].Value = "Meow"; 
     e.Row.Cells["Dog"].Value = "Woof"; 

     // This line will commit the new line to the binding source 
     dgv.BindingContext[dgv.DataSource].EndCurrentEdit(); 
    } 

, 우리는 그것이 작동하지 않기 때문에 DefaultValuesNeeded 이벤트를 사용하지 않을 수 있습니다. 그러나 CellEnter 이벤트를 캡처하여 시뮬레이션 할 수 있습니다.

{ 
     dataGridView1.Columns.Add("Cat", "Cat"); 
     dataGridView1.Columns.Add("Dog", "Dog"); 

     dataGridView1.AllowUserToAddRows = true; 
     dataGridView1.CellEnter += dataGridView1_CellEnter;  
    } 

    void dataGridView1_CellEnter(object sender, DataGridViewCellEventArgs e) 
    { 
     var dgv = sender as DataGridView; 
     if (dgv == null) 
      return; 

     var row = dgv.Rows[e.RowIndex]; 

     if (row.IsNewRow) 
     { 
      // Set your default values here 
      row.Cells["Cat"].Value = "Meow"; 
      row.Cells["Dog"].Value = "Woof"; 

      // Force the DGV to add the new row by marking it dirty 
      dgv.NotifyCurrentCellDirty(true); 
     } 
    } 
+0

고맙지 만, 소스를 바인딩하지 않았습니다. 사용자가 필드를 편집하고 새 행을 추가하여 데이터를 내 gridview에 추가합니다. – tulkas85

+0

@ tulkas85 바인딩 소스없이 작업하는 방법에 대한 단원을 추가했습니다. – Moop

관련 문제