2014-11-24 5 views
1

Windows Forms 응용 프로그램 사용.처음에 새 DataGridViewRow를 삽입 할 때 마지막 DataGridViewRow를 제거하는 방법은 무엇입니까?

public class CustomDataGridView : DataGridView 
{ 
    private int maxRowsAllowed = 3; 

    public CustomDataGridView() 
    { 
     this.AutoGenerateColumns = false; 
     this.AllowUserToAddRows = false; 
     this.AllowUserToDeleteRows = false; 
     this.ReadOnly = true; 
     this.RowsAdded += CustomDataGridView_RowsAdded; 
     this.SelectionMode = DataGridViewSelectionMode.FullRowSelect; 
    } 

    public void Start() 
    { 
     this.Columns.Add("col1", "header1"); 
     this.Columns.Add("col2", "header2"); 

     // rows added manually, no DataSource 
     this.Rows.Add(maxRowsAllowed); 
    } 

    private void customDataGridView_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e) 
    { 
     // At this point, while debugging, I realized that CurrentRow is null, 
     // doing impossible to change it to a previous one, this way avoiding an exception. 
     if (this.Rows.Count > maxRowsAllowed) 
     { 
      this.Rows.RemoveAt(maxRowsAllowed); 
     } 
    } 
} 

그리고, 컨테이너 클래스로부터 AddRowAtBeginning있어서 내부 새로운 행이 다른 하나의 인덱스를 이동 0 인덱스에 삽입되어
는 I는 DataGridView 제어로부터 도출이 클래스를 갖는다.
RowsAdded 이벤트가 발생하고 실제 총 행 수가 보다 큰 경우 인 경우 마지막이 제거됩니다. 변위로 인해 (헤더 작은 화살표)를 CurrentRow이 제거 될 때까지 선택이 끝난

public class ContainerForm : Form 
{ 
    private CustomDataGridView dgv; 

    public ContainerForm() 
    { 
     InitializeComponent(); 

     dgv = new CustomDataGridView(); 

     dgv.Size = new Size(400, 200); 
     dgv.Location = new Point(10, 10); 
     this.Controls.Add(dgv); 

     dgv.Start(); 
    } 

    // Inserts a row at 0 index 
    private void aButton_Click(object sender, EventArgs e) 
    { 
     var newRow = new DataGridViewRow(); 
     newRow.DefaultCellStyle.BackColor = Color.LightYellow; 

     dgv.Rows.Insert(0, newRow); 
    } 
} 

모든 것이 OK이다.

나는 RowsAdded이 도망 칠 때 System.ArgumentOutOfRangeException이 던져진 이유는 dgv.Rows.Insert(0, newRow) 줄로 돌아가려고 생각합니다.

아직 해결책을 찾을 수 없습니다. 이 문제를 우회하기 쉽습니다 동안

+0

if (this.Rows.Count > maxRowsAllowed) { this.Rows.RemoveAt(maxRowsAllowed); } 

을 변경하려고; 수정 중 하나는'customDataGridView_RowsAdded'의 코드를'aButton_Click' 메소드의 끝으로 옮기고'dgv.Rows.Insert (0, newRow);'뒤에 삽입하는 것입니다. – kennyzx

+0

물론, 당신의 제안은 옳습니다. 그러나 그런 식으로,'ContainerForm'은'maxRowsAllowed' 값을 알아야합니다. 이것은 피하려고하는 것입니다. – Shin

답변

0

내가 그것의 근본 원인을 모르는,이

if (this.Rows.Count > maxRowsAllowed) 
{ 
    // if the number of rows is 10 
    // the index of the last item is 9 
    // index 10 is out of range 
    this.Rows.RemoveAt(maxRowsAllowed -1); 
} 
+0

아니요, 이것이 문제의 원인이 아닙니다. Row.Count가 10보다 큰 경우 (maxRowsAllowed), datagridview는 적어도 11 개의 행을 가져야하고,'this.Rows.RemoveAt (10)'은 범위 예외를 throw하지 않습니다. – kennyzx