[英]Null pointer when switching between data grids
在我正在编写的程序中,wpf表单上有两个数据网格。 一个包含宠物主人,另一个包含实际的宠物。 当用户单击所有者时,宠物数据网格将通过SQL数据库填充他们拥有的宠物。 当前选择的所有者ID将保存到变量中。 用户单击宠物时,将执行同样的操作,将宠物ID保存到变量中。
现在,我遇到的问题是当选择主人宠物时。 单击其他所有者时,出现空指针异常,但我不确定原因。
以下是一些代码。 它在PetDg_SelectionChanged方法上崩溃。 任何帮助,将不胜感激。 谢谢!
public partial class UpdateWindowNew : Window
{
int currentOwnerPk;
int currentPetPk;
public UpdateWindowNew()
{
InitializeComponent();
}
public void Window_Loaded(object sender, RoutedEventArgs e)
{
string conString = ConfigurationManager.ConnectionStrings["conString"].ConnectionString;
string cmdString = "empty";
using (SqlConnection con = new SqlConnection(conString))
{
cmdString = "Select * from Owner";
SqlCommand query = new SqlCommand(cmdString, con);
SqlDataAdapter gridAdapter = new SqlDataAdapter(query);
DataTable dt = new DataTable("Owner");
gridAdapter.Fill(dt);
ownerDg.ItemsSource = dt.DefaultView;
}
}
private void ownerDG_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
currentOwnerPk = (int)(ownerDg.SelectedItem as DataRowView).Row.ItemArray[0];
OwnerFname.Text = (string)(ownerDg.SelectedItem as DataRowView).Row.ItemArray[1];
OwnerLname.Text = (string)(ownerDg.SelectedItem as DataRowView).Row.ItemArray[2];
showOwnedPets(currentOwnerPk);
}
private void PetDg_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
currentPetPk = (int)(PetDg.SelectedItem as DataRowView).Row.ItemArray[0];
}
这非常简单,因为当您选择另一个所有者时,pet DataGrid变空并引发此异常,因此您需要在PetDg_SelectionChanged事件处理程序中检查所选项目的空值:
currentPetPk = PetDg.SelectedItem is DataRowView item ?
(int)item.Row.ItemArray[0] : -1;
SelectedItem可能为null。 您应该使用空条件运算符'?。'进行检查。
currentOwnerPk = (int)(ownerDg?.SelectedItem as DataRowView)?.Row.ItemArray[0] ?? -1;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.