错误消息"无法转换类型&#34的对象;

时间:2016-07-21 12:09:45

标签: c# .net winforms datagridview

我有datagridview和三个文本框。当引起网格事件SelectionChanged时,我从网格获取数据并写入属性。当您没有单击列具有值时,会出现问题。

 private void _artistGridSelectionChanged(object sender, EventArgs e)
{  
    int rowIndex = ArtistListGrid.CurrentCell.RowIndex;
    int cellIndex = ArtistListGrid.CurrentCell.ColumnIndex;

    this.ID = ((DataRowView)BSource.Current).Row.Field<Int32>("ID");
    this.Name = ((DataRowView)BSource.Current).Row.Field<string>("Firstname");
    this.Lastname = ((DataRowView)BSource.Current).Row.Field<string>("Lastname");
    this.Nickname = ((DataRowView)BSource.Current).Row.Field<string>("Nickname");
} 

如何解决这个问题:

enter image description here

屏幕截图中的文字:无法投射类型为&System;对象的系统.Windows.Forms.DataGridView&#39;输入&#39; System.Windows.Forms.DataRowView&#39;。

1 个答案:

答案 0 :(得分:1)

请参阅is运营商:https://msdn.microsoft.com/en-us/library/scekt9xw.aspx

检查它是否是DataRowView:

if(BSource.Current is DataRowView)
{
  //...do your cast here

或者,您可以使用as运算符:

https://msdn.microsoft.com/en-us/library/cscsdfbt.aspx