在我正在編寫的程序中,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];
}
非常感謝!你的答案和Peter Bruins都工作。 – Mystified
我已編輯此答案來格式化代碼 –