【问题标题】:StackOverflowException when changing DataGridViewButtonCell value更改 DataGridViewButtonCell 值时出现 StackOverflowException
【发布时间】:2016-03-27 13:29:42
【问题描述】:

我正在开发一个使用DataGridView 控件的Windows 窗体应用程序。这个DataGridView 有一个包含按钮的单元格。默认按钮文本是 Start 但当我尝试动态更改它时:

((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";
             }
     }
}

【问题讨论】:

  • 问题是你从哪里打电话给HighlightOnlineUsers
  • @IvanStoev 它在Form 的代码文件中,DataGridView 位于其中。
  • 我的意思是,看起来你是从某个事件中调用它,并且实现触发了相同的事件,因此 StackOverflowException。
  • @IvanStoev 我从dataGridView1_CellFormatting 事件中调用它。也来自其他改变数据的事件。
  • 这就是导致异常的原因,每次格式更新都会触发dataGridView1_CellFormatting 事件,当您在此方法中更新CellFormat 时,这会产生递归。

标签: c# .net winforms button datagridview


【解决方案1】:

要为按钮设置不同的文本,您可以处理网格的CellFormatting 事件,并将用于格式化列值的逻辑放在那里。

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;

【讨论】:

  • 这行得通。但我可能也想从dataGridView1_Sorted 事件中调用它。我该怎么做?
  • 我认为在单元格格式化事件中有这样的代码就足够了。如果您需要排序或其他方面的特定要求,请随时提出另一个问题,我作为其他社区成员将尽力帮助您解决问题。 :)
  • 非常感谢您的帮助。如果排序期间的格式化不能正常工作,我会问另一个问题。 :)
【解决方案2】:
for (int i = 0; i < dataGridView1.RowCount; i++)
{
  dataGridView1.Rows[i].Cells["Buttons"].Value = "some value";
}

注意"Buttons"是列名

【讨论】:

  • 它与我的方法有何不同?
猜你喜欢
  • 2016-09-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-02-25
相关资源
最近更新 更多