2012-06-29 3 views
3

여기에 무슨 일이 일어나는지 알 수없는 것처럼 보입니다. 주어진 시간에 500 행 이상이 아닌 보통 200 또는 300의 dataGridView가 있습니다. 그리드를 반복합니다. 사용자 상호 작용에 따라 버튼 텍스트와 색상을 설정할 수 있습니다. 예 :DataGridView 셀에 값을 할당 할 때 느려짐

using System; 
using System.Collections.Generic; 
using System.ComponentModel; 
using System.Data; 
using System.Drawing; 
using System.Linq; 
using System.Text; 
using System.Windows.Forms; 

namespace WindowsFormsApplication1 
{ 
    public partial class Form1 : Form 
    { 
     DataGridViewButtonColumn btn; 
     ContextMenuStrip ctxtStartStop; 

     public Form1() 
     { 
      InitializeComponent(); 

      formatGrid(); 
      populateGrid(); 

      ctxtStartStop = new ContextMenuStrip(); 
      ctxtStartStop.Items.Add("START ALL"); 
      ctxtStartStop.Items.Add("STOP ALL"); 
      ctxtStartStop.ItemClicked += new ToolStripItemClickedEventHandler(ctxtMenuStrip_ItemClicked); 
     } 

     private void formatGrid() 
     { 
      btn = new DataGridViewButtonColumn(); 
      btn.Text = "START"; 
      btn.Name = "colStartStop"; 
      btn.HeaderText = "Start/Stop"; 
      btn.DefaultCellStyle.BackColor = Color.LightGreen; 
      btn.DefaultCellStyle.ForeColor = Color.Black; 
      btn.ReadOnly = false; 
      btn.UseColumnTextForButtonValue = false; 
      btn.FlatStyle = FlatStyle.Standard; 
      btn.AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells; 

      gridDisplay.AutoGenerateColumns = false; 
      gridDisplay.AllowUserToAddRows = false; 
      gridDisplay.RowHeadersVisible = false; 
      gridDisplay.Columns.Add(new DataGridViewTextBoxColumn() 
      { 
       Name = "colSymbol", 
       HeaderText = "Symbols", 
       ReadOnly = true, 
       AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill, 
       MinimumWidth = 50 
      }); 
      gridDisplay.Columns.Add(btn); 

      gridDisplay.MouseClick += new MouseEventHandler(gridDisplay_MouseClick); 
     } 

     private void populateGrid() 
     { 
      for (int i = 0; i < 500; i++) 
      { 
       gridDisplay.Rows.Add("XYZ", "START"); 
      } 
     } 

     private void gridDisplay_MouseClick(object sender, MouseEventArgs e) 
     { 
      if (e.Button == System.Windows.Forms.MouseButtons.Left) 
       return; 

      int rowPosition = gridDisplay.HitTest(e.X, e.Y).RowIndex; 
      int colPosition = gridDisplay.HitTest(e.X, e.Y).ColumnIndex; 

      if (rowPosition == -1 && colPosition == 1) 
      { 
       ctxtStartStop.Show(gridDisplay.PointToScreen(e.Location)); 
      } 
     } 

     private void ctxtMenuStrip_ItemClicked(object sender, ToolStripItemClickedEventArgs e) 
     { 
      if (e.ClickedItem.Text == "START ALL") 
      { 
       ctxtStartStop.Hide(); 
       startAll(); 
      } 
      else if (e.ClickedItem.Text == "STOP ALL") 
      { 
       ctxtStartStop.Hide(); 
       stopAll(); 
      } 
     } 

     private void startAll() 
     { 
      string action = string.Empty; 
      int idx = 1; 

      for (int i = 0; i < gridDisplay.Rows.Count; i++) 
      { 
       var btnCell = gridDisplay.Rows[i].Cells[idx]; 

       action = (string)btnCell.Value; 

       if (action == "START") 
       { 
        btnCell.Value = "STOP"; 
        gridDisplay.Rows[i].Cells["colStartStop"].Style.BackColor = Color.Red; 
        gridDisplay.Rows[i].Cells["colStartStop"].Style.ForeColor = Color.White; 
       } 
      } 
     } 

     private void stopAll() 
     { 
      string action = string.Empty; 
      int idx = 1; 

      for (int i = 0; i < gridDisplay.Rows.Count; i++) 
      { 
       var btnCell = gridDisplay.Rows[i].Cells[idx]; 

       action = (string)btnCell.Value; 

       if (action == "STOP") 
       { 
        btnCell.Value = "START"; 
        gridDisplay.Rows[i].Cells["colStartStop"].Style.BackColor = Color.LightGreen; 
        gridDisplay.Rows[i].Cells["colStartStop"].Style.ForeColor = Color.Black; 
       } 
      } 
     } 
    } 
} 

재미있는 점은 색상 설정이 잘 작동하지만 값을 설정할 때 매우 느리게 실행된다는 것입니다.

누군가 내가 여기서 잘못하고있는 것을 설명해 줄 수 있습니까?

는 -DA

+0

읽을 수 없거나 해결하기가 쉽지 않기 때문에 더 좋은 코드 레이아웃/형식으로 코드를 게시 할 수 있습니까 – JohnnBlade

+0

관련 값 (소스를 변경)을 사용하여 '데이터 소스'를 만들 수 없으며 바인딩 할 수 있습니까? 'CellFormatting' 이벤트의 색상 – V4Vendetta

+0

똑같은 문제가 너무 커서이 포스트를 발견했습니다. MyClass의 메모리 사전에있는 DataGridView에 각각 12 개의 셀이있는 400 개의 행을 추가하면 15 초가 소요됩니다. 하지만이 두 줄의 코드를 추가하면 "dgv_mainlist.Rows [r_index] .Cells [3] .Value =" ";" 모든 것을 실행하려면 1 초 이상 걸립니다. 행당 2 개의 셀에 값을 추가하여 거의 5-6 배 더 길게. - 3 년이 게시물에 아직 대답 ... 나는 내 숨을 참지 않을 것 같아요. 컨트롤에 문제가있는 것 같습니다. –

답변

4

나는 너무 된 DataGridView에서 셀 값을 변경하고 속도 저하를 경험하고 있었다, 감사합니다. 행을 삽입 한 후 행 당 2 개의 값을 변경했을 때로드하는 데 5-6 배의 시간이 걸렸습니다. 지정 상기 재산 - Evidentally DataGridView에 컬럼이 값은 모든 텍스트를 확인하기 위해 셀이 변경 될 때마다 너비 표시 재 계산

dgv_mainlist.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells; 

:

날의 문제는 다음과 같은 속성이다. 내 코드에서 스톱워치를 사용하면 약 12 ​​개의 셀이있는 400 개의 행을로드하는 데 약 1 초가 걸립니다.

dgv_mainlist.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.None; 

이제 내 DataGridView를로드하는 데 약 0.05 초 정도 걸립니다 :

는 그럼 난에 속성을 설정합니다. 20 배 빨라졌습니다!

물론 다른 옵션은 각 행을 삽입 할 때 셀 값을 입력하는 것이지만 내 경우에는 불가능합니다.

위의 autosize 속성을 "AllCells"로 설정해야하는 경우 값을 변경하기 전에 자동 크기를 "없음"으로 설정 한 다음 값을 완료하면 "AllCells"로 설정할 수 있습니다. 그것은 내로드 시간에 거의 1 초를 더한 전체 시간을 "AllCells"로 설정하는 것보다 훨씬 좋은 내로드 시간에만 0.1 초를 더했습니다.

답을 찾는데 도움이되었으므로 신용 한도는 this page입니다.

메모 추가 : 내 DataGridView가 데이터 소스에 바인딩되지 않았습니다. 행은 코드의 루프를 통해 삽입됩니다.

0

자동 크기 조절 모드를 없음으로 설정하십시오.

paginationGirdView.Columns["colActualTime"].AutoSizeMode = DataGridViewAutoSizeColumnMode.None; 

//assign value 

row.Cells["colActualTime"].Value = "yesterday"; 
paginationGirdView.Columns["colActualTime"].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells; 

이렇게하면 문제가 해결됩니다.

+0

그냥 테스트했는데 원래 속도보다 느리거나 느리지 않으면 성능에 전혀 영향을주지 않습니다. – IamBatman

관련 문제