Hello.
I am trying to simply populate a ComboBox with data from a Sql server table column (adhering to the MVVM design pattern), and do not understand why it is not working. I am binding it to a BindableCollection (Stylet framework), which is basically an ObservableCollection.
There is automatic coupling between the View and the ViewModel (Stylet does this).
This is my method:
public void FillComboBoxLicenseHolders() {
try {
DataSet ds = new DataSet();
using (SqlConnection sqlCon = new SqlConnection(ConnectionString.connectionString)) {
SqlDataAdapter sqlDA = new SqlDataAdapter();
sqlDA.SelectCommand = new SqlCommand("select Foretaksnavn from tblLicenseHolder", sqlCon);
sqlDA.Fill(ds);
}
DataTable dt = new DataTable();
dt = ds.Tables[0];
for (int i = 0; i < dt.Rows.Count; i++) {
DataRow dr = dt.NewRow();
dr = dt.Rows[i];
LicenseHolder licenseHolder = new LicenseHolder();
licenseHolder.Foretaksnavn = dr["Foretaksnavn"].ToString();
LicenseHolders.Add(licenseHolder);
}
} catch (Exception ex) {
MessageBox.Show(ex.Message, "Message", MessageBoxButton.OK, MessageBoxImage.Information);
}
}
This is how I instantiate my BindableCollection:
private BindableCollection<LicenseHolder> _licenseHolders;
public BindableCollection<LicenseHolder> LicenseHolders {
get => _licenseHolders;
set => SetAndNotify(ref this._licenseHolders, value);
}
public TripViewModel(IWindowManager windowManager) {
this.windowManager = windowManager;
LicenseHolders = new BindableCollection<LicenseHolder>();
}
This is my ComboBox in the XAML:
<ComboBox Name="cbLicenseHolder" Canvas.Left="50" Canvas.Top="204" Width="291"
ItemsSource="{Binding LicenseHolders, Mode=TwoWay}"
Loaded="{s:Action FillComboBoxLicenseHolders}"/>
What I have tried:
I've spent the better part of a day trying to Google my way through this..
When I run my app, there's no error message, but the ComboBox displays no results.
If I debug and put a break point, I can see that it does indeed read the sql server column data, but it is still not showing.
Any ideas?