Hello!
I am writing a business application in WPF, adhering to the MVVM design principles.
What I am trying to do:
I have two ComboBoxes in a View. I want the 2nd one to be filtered based on the SelectedItem/Value in the first one.
I can't figure out how to do that from the ViewModel. This is what I've got so far:
My first ComboBox:
<ComboBox Name="cbLicenseHolder" Canvas.Left="50" Canvas.Top="204" Width="291"
ItemsSource="{Binding LicenseHolders, Mode=TwoWay}"
Loaded="{s:Action FillComboBoxLicenseHolders}"
DisplayMemberPath="Foretaksnavn"
SelectedValue="{Binding CbLicenseHolderSelection, UpdateSourceTrigger=PropertyChanged}"
FontSize="12" SelectionChanged="cbLicenseHolder_SelectionChanged"
/>
My second ComboBox:
<ComboBox Name="cbVehicle" Canvas.Left="381" Canvas.Top="204" Width="269"
ItemsSource="{Binding Licenses, Mode=TwoWay}"
Loaded="{s:Action FillComboBoxLicenses}"
FontSize="12"
IsEnabled="False"/>
"CbLicenseHolderSelection" is a property holder in my ViewModel:
private string _cbLicenseHolderSelection;
public string CbLicenseHolderSelection {
get { return this._cbLicenseHolderSelection; }
set { SetAndNotify(ref this._cbLicenseHolderSelection, value); }
}
Now, for the loaded event, you can see I am using Stylets (framework) "s:Action" function, to fire off my "FillComboBoxLicenses" -method, which looks like this:
public void FillComboBoxLicenses() {
try {
DataSet ds = new DataSet();
using (SqlConnection sqlCon = new SqlConnection(ConnectionString.connectionString)) {
SqlDataAdapter sqlDA = new();
sqlDA.SelectCommand = new SqlCommand("fillLicensesComboBox", sqlCon);
sqlDA.SelectCommand.CommandType = CommandType.StoredProcedure;
sqlDA.SelectCommand.Parameters.Add("@Foretaksnavn", SqlDbType.NVarChar).Value = CbLicenseHolderSelection.ToString();
sqlDA.Fill(ds);
}
DataTable dt = new();
dt = ds.Tables[0];
for (int i = 0; i < dt.Rows.Count; i++) {
DataRow dr = dt.NewRow();
dr = dt.Rows[i];
License license = new();
license.KjøretøyID = dr["KjøretøyID"].ToString();
Licenses.Add(license);
}
} catch (Exception ex) {
MessageBox.Show(ex.Message, "Message", MessageBoxButton.OK, MessageBoxImage.Information);
}
}
But I get the error message saying: 'Object reference not set to an instance of an object.' I guess because I haven't been able to make a selection in ComboBox1 before it fires off.
How can I make sure my method fires of only when there's been made a selection in the first ComboBox?
Thanks!!