前端代码:
<ListView Name="lvCus" MouseDoubleClick="ListViewItem_DoubleClick">
<ListView.View>
<GridView AllowsColumnReorder="true" ColumnHeaderToolTip="TbCus">
<GridViewColumn Header="CusID" Width="40" DisplayMemberBinding="{Binding Path=CusID}" />
<GridViewColumn Header="Firstname" Width="120" DisplayMemberBinding="{Binding Path=fn}" />
<GridViewColumn Header="Lastname" Width="120" DisplayMemberBinding="{Binding Path=ln}" />
<GridViewColumn Header="Dob" Width="100" DisplayMemberBinding="{Binding Path=dob}" />
<GridViewColumn Header="Age" Width="60" DisplayMemberBinding="{Binding Path=age}" />
</GridView>
</ListView.View>
</ListView>
以下是后端的代码:
private void ListViewItem_DoubleClick(object sender, RoutedEventArgs e)
{
System.Data.DataRowView cusObj = (System.Data.DataRowView)lvCus.SelectedItem;
var myobj = cusObj.Row.ItemArray;
txtCusID.Text = myobj[0].ToString();
txtfn.Text = myobj[1].ToString();
txtln.Text = myobj[2].ToString();
txtdob.Text = myobj[3].ToString();
txtage.Text = myobj[4].ToString();
}
ListView加载了数据,最后似乎有一个空行。当我点击ListView的空行时,我得到以下错误:
WpfApp.exe中出现'System.InvalidCastException'类型的第一次机会异常
其他信息:无法将“MS.Internal.NamedObject”类型的对象强制转换为“System.Data.DataRowView”。
如果存在此异常的处理程序,则可以安全地继续该程序。
我遇到了上述错误,我该如何解决?伙计们,我正在学习阶段。
答案 0 :(得分:1)
您应该使用as运算符来确保SelectedItem属性实际返回System.Data.DataRowView,以避免在用户双击最后一行时出现异常:
private void ListViewItem_DoubleClick(object sender, RoutedEventArgs e)
{
System.Data.DataRowView cusObj = lvCus.SelectedItem as System.Data.DataRowView;
if (cusObj != null)
{
var myobj = cusObj.Row.ItemArray;
txtCusID.Text = myobj[0].ToString();
txtfn.Text = myobj[1].ToString();
txtln.Text = myobj[2].ToString();
txtdob.Text = myobj[3].ToString();
txtage.Text = myobj[4].ToString();
}
}