【问题标题】:Unable to cast object of type 'System.Data.DataRowView' to type xxx无法将“System.Data.DataRowView”类型的对象转换为 xxx 类型
【发布时间】:2012-01-23 00:07:32
【问题描述】:

我想在我的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();    
}

【问题讨论】:

  • 不确定,但我假设通过将List 转换为DataTable,您会丢失实际的Player 实例 - 尝试使用PlayerList[row].KillPlayer(); 直接访问该实例并查看它是否有效。
  • 这在很大程度上取决于 Tools.ToDataTable 的作用。

标签: c# .net winforms collections datagridview


【解决方案1】:
private void DataGridView1_CellContentDoubleClick(object sender, DataGridViewCellEventArgs e)
{
   Player player = DataGridView1.Rows[e.RowIndex].DataBoundItem as Player;
}

【讨论】:

    【解决方案2】:

    只是想一想,你真的需要转换为 DataTable 吗?

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

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

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

    【讨论】:

    • 是的。我需要使用数据表。我需要排序。
    • 您是否考虑过/尝试将类型化的数据集添加到表单中并将 Grid DataSource 设置为该数据集,然后填充该 DataSet 而不是 PlayerList。这应该可以满足您的需求。
    • 你也可以对其他数据结构进行排序,你知道的。
    猜你喜欢
    • 1970-01-01
    • 2012-03-14
    • 1970-01-01
    • 1970-01-01
    • 2013-07-10
    • 2014-10-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多