2016-03-27 25 views
1

DataGridViewコントロールを使用するWindowsフォームアプリケーションを開発しています。このDataGridViewには、ボタンを含むセルがあります。デフォルトボタンのテキストはStartですが、私は次のように動的に変更しようとすると:DataGridViewButtonCell値を変更するとStackOverflowExceptionが発生する

((DataGridViewButtonCell)Myrow.Cells[9]).Value = "End"; 

または単に

Myrow.Cells[9].Value = "End"; 

ようですが、次の例外スロー:私の完全なコードは次のようである

An unhandled exception of type 'System.StackOverflowException' occurred in System.Windows.Forms.dll 

をこれは:

void HighlightOnlineUsers() 
{ 
    foreach (DataGridViewRow Myrow in dataGridView1.Rows) 
    { 
      if (Convert.ToInt32(Myrow.Cells[8].Value) > 0) 
      { 
        Myrow.DefaultCellStyle.BackColor = Color.GreenYellow; 
        Myrow.Cells[9].Value = "End"; 
      } 
      else { 
        Myrow.DefaultCellStyle.BackColor = Color.White; 
        ((DataGridViewButtonCell)Myrow.Cells["SessionAction"]).Value = "Start"; 
      } 
    } 
} 
+1

をあなたは –

+0

から 'HighlightOnlineUsers'を呼ぶのですどこの質問は、それは' Form'のコードファイル内にあります@IvanStoevた 'DataGridViewの中'が置かれている。 –

+1

私は、あなたが何らかのイベントから呼び出すように見え、実装が同じイベントをトリガーするので、StackOverflowExceptionが発生します。 –

答えて

3

の名前です。

private void grid_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e) 
{ 
    //If this is header row or new row, do nothing 
    if (e.RowIndex < 0 || e.RowIndex == this.grid.NewRowIndex) 
     return; 

    //I suppose your button is at index 9 
    if (e.ColumnIndex == 9) 
    { 
     //You can put your dynamic logic here 
     //and use different values based on other cell values 
     //for example based on cell at index 8  
     if (Convert.ToInt32(this.grid.Rows[e.RowIndex].Cells[8].Value) > 0) 
      e.Value = "End"; 
     else 
      e.Value = "Start"; 
    } 
} 

あなたはCellFormatingイベントにこのハンドラを割り当てる必要があります。

this.grid.CellFormatting += grid_CellFormatting; 
+0

それは働いている。しかし、これを 'dataGridView1_Sorted'イベントから呼び出すこともできます。どうやってやるの? –

+1

私は、セルの書式設定イベントでこのようなコードを持つだけで十分だと思います。あなたが並べ替えや他の何かのための特定の要件を必要とする場合は、別の質問をする気軽に、私は他のコミュニティのメンバーがあなたの問題を解決するためにお手伝いをしようとします。 :) –

+0

ありがとうございました。並べ替え中に書式設定が正しく機能しない場合、別の質問をします。 :) –

0
for (int i = 0; i < dataGridView1.RowCount; i++) 
{ 
    dataGridView1.Rows[i].Cells["Buttons"].Value = "some value"; 
} 

"Buttons"はあなたのグリッドのCellFormattingイベントを処理し、そこに列の値をフォーマットするためのロジックを置くことができ、ボタンに別のテキストを持っているために、列

+0

私のアプローチとどのように違うのですか? –

+0

Aargh!その通り。私はあなたのコードを正しく読まなかった。 – Eminem

関連する問題