Hello!
So, I have a WPF-app.
I've tried to set it up using the
MVVM design pattern
. Keyword:
tried.
I've a
ViewModel
(RidelHubMainViewModel), and several
windows
/
views
.
In one of my
windows
(LicenseHoldersWindow), I've a
DataGrid
. It's hooked up to
Sql-server
and bound using an
ObservableCollection
. So far; all good.
I've been going back and forth trying to implement new functionality, like adding rows to the
DataGrid
, and removing them. Adding rows is done through opening up a
child-window
and adding the data into textboxes.
But then I realized my
method
to add new rows to the
Sql-server
and update the
ObservableCollection
was not adhering to the
MVVM design pattern
. So I tried to move it to the
ViewModel
.
I did, and now the method can't read my textbox-value references.
So, I tried to create an instance of the
child-form
, like such:
NewLicenseHolderWindow nlh = Application.Current.Windows.OfType<NewLicenseHolderWindow>().FirstOrDefault();
But when I run my app and try to add the new row to the
DataGrid
(by clicking a 'Save'-button in the
child-window
, which also closes the
child-window
(and returns me to the
window
with the
DataGrid
, I get the following error message:
Quote:
System.NullReferenceException: 'Object reference not set to an instance of an object.'
nlh was null.
So, I am obviously not grabbing the current instance of the
child-window
, right?
How can I do that?
For reference, the way I update the
DataGrid
is by using an
ICommand
. It looks like this:
private void ExecuteRefreshCommand() {
NewLicenseHolderWindow nlh =
Application.Current.Windows.OfType<NewLicenseHolderWindow>().FirstOrDefault();
if (LicenseHolders == null) {
LicenseHolders = new ObservableCollection<LicenseHolder>();
} else {
AddToDB();
LicenseHolders.Clear();
LicenseHolders.Add(new LicenseHolder() { Foretaksnavn =
nlh.txtForetaksnavn.Text.ToString() });
OnLicenseHoldersPropertyChanged();
}
}
public void AddToDB() {
string sqlString = "insert into tblLicenseHolder (Foretaksnavn, /* more of the same
*/) values (@Foretaksnavn, /* more of the same */)";
NewLicenseHolderWindow nlh =
Application.Current.Windows.OfType<NewLicenseHolderWindow>().FirstOrDefault();
try {
using (SqlConnection sqlCon = new(ConnectionString.connectionString))
using (SqlCommand sqlCmd = new(sqlString, sqlCon)) {
sqlCon.Open();
if (string.IsNullOrEmpty(nlh.txtForetaksnavn.Text)
textboxes {
MessageBox.Show("Vennligst fyll ut alle tekstboksene.");
sqlCon.Close();
} else {
sqlCmd.Parameters.AddWithValue("@Foretaksnavn",
nlh.txtForetaksnavn.Text.ToString());
sqlCmd.ExecuteNonQuery();
MessageBox.Show("Ny løyvehaver lagret. Husk å oppdatere listen.");
}
}
}
catch (Exception ex) {
MessageBox.Show(ex.Message, "Message", MessageBoxButton.OK, MessageBoxImage.Information);
}
}
Sorry for the long read...
Hopefully this makes sense to anyone.
What I have tried:
Honestly, I've moved the code around, tried to adapt it, modify it - in so many ways - that I've lost count.
Thanks in advance!