在数据网格之间切换时为空指针

时间:2017-04-16 08:23:33

标签: c# wpf datagrid

在我正在编写的程序中,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];
    }

2 个答案:

答案 0 :(得分:1)

非常简单,因为当你选择另一个所有者时,pet DataGrid变为空并触发此异常,你需要检查PetDg_SelectionChanged事件处理程序中所选项的空值:

currentPetPk = PetDg.SelectedItem is DataRowView item ?
    (int)item.Row.ItemArray[0] : -1;

答案 1 :(得分:1)

SelectedItem可能为null。您应该使用Null条件运算符'?'来检查它。

currentOwnerPk = (int)(ownerDg?.SelectedItem as DataRowView)?.Row.ItemArray[0] ?? -1;