无法强制类型为'System.Data.DataRowView'输入xxx

本文关键字:Data DataRowView 输入 xxx System 类型 | 更新日期: 2023-09-27 18:18:06

我想访问我的DataGridView中的Player对象。这就是我如何将我的玩家列表绑定到DataGridView:

PlayerList = new List<Player>(players);
//Populate Player list heere (...)          
DataTable dt = Tools.ToDataTable<Player>(PlayerList);
Grid.DataSource = dt;

现在我想访问我的Player对象在选定行双击事件:

private void Grid_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
{
    if (Grid.SelectedCells == null)
    {
        return;
    }
    int row = Grid.SelectedCells[0].RowIndex;
    //Here I get that exception from the title
    ((Player)(Grid.Rows[row].DataBoundItem)).KillPlayer();    
}

无法强制类型为'System.Data.DataRowView'输入xxx

只是一个想法,你真的需要转换成一个数据表吗?

您应该能够通过Grid.DataSource = PlayerList;PlayerList直接绑定到Grid.DataSource

PlayerList = new List<Player>(players);
//Populate Player list heere (...)          
Grid.DataSource = PlayerList;

你的代码((Player)(Grid.Rows[row].DataBoundItem)).KillPlayer();应该可以正常工作。

private void DataGridView1_CellContentDoubleClick(object sender, DataGridViewCellEventArgs e)
{
   Player player = DataGridView1.Rows[e.RowIndex].DataBoundItem as Player;
}