-1

How can I save the info that the ViewModel/Model passes to the View? I need this info saved to a database but just to ensure the values are being retrieved, I've set up a MessageBox to show if the value is being retrieved.

This is the code for my ViewModel/Model:

namespace OcelotPayroll
{
    public class PayslipModel : EmployeeModel
    {

        private decimal statIncome;
        private string totalDed;
        private string _netpay;
        private string _amount;

        public string Amount
        {
            get
            {
                return _amount;
            }
            set
            {
               _amount = value;
               OnPropertyChanged("Amount");
            }
        }


        public decimal StautoryIncome
        {
            get
            {
                return statIncome;
            }
            set
            {
                statIncome = value;
            }
        }

        public PayslipModel()
        {

            Date = DateTime.Today.Date;

            SelectAll = new DelegateCommand(Select, () => CanSelect);

            UnSelectAll = new DelegateCommand(UnSelect, () => CanUnSelect);

            SaveToDatabase = new DelegateCommand(Save, () => CanSave);

            scon = new MichaelAllenEntities();

        }

        public ICommand SaveToDatabase
        {
            get; set;
        }

        private bool CanSave
        {
            get { return Workspaces.Count > 0; }
        }

        private async void Save()
        {
            try
            {
                MessageBox.Show(StautoryIncome.ToString()); //returns 0
                MessageBox.Show(Amount.ToString()); //NullPointerException
            }
            catch (DbEntityValidationException ex)
            {
                foreach (var en in ex.EntityValidationErrors)
                {
                    var exceptionDialog = new MessageDialog
                    {
                        Message = { Text = string.Format("{0}, {1}", en.Entry.Entity.GetType().Name, en.Entry.State) }
                    };

                    await DialogHost.Show(exceptionDialog, "RootDialog");

                    foreach (var ve in en.ValidationErrors)
                    {
                        exceptionDialog = new MessageDialog
                        {
                            Message = { Text = string.Format("{0}, {1}", ve.PropertyName, ve.ErrorMessage) }
                        };

                        await DialogHost.Show(exceptionDialog, "RootDialog");
                    }
                }
            }
            catch(Exception ex)
            {
                var exceptionDialog = new MessageDialog
                {
                    Message = { Text = string.Format("{0}", ex) }
                };

                await DialogHost.Show(exceptionDialog, "RootDialog");
            }

        }

        public async void CalcNis()
        {
            try
            {
                float nis = 0;

                NisName = "N.I.S.";

                SqlConnection con = new SqlConnection(scon.Database.Connection.ConnectionString);
                con.Open();
                SqlCommand cmd = new SqlCommand("select NIS from Deductions where TaxId='1'", con);

                SqlDataReader sdr = cmd.ExecuteReader();
                while (sdr.Read())
                {
                    nis = float.Parse(sdr.GetValue(0).ToString());
                }

                con.Close();

                if (Amount != string.Empty)
                {
                     NisVal = (decimal.Parse(Amount.ToString()) * decimal.Parse(nis.ToString())).ToString("N2");
                     StautoryIncome = (decimal.Parse(Amount.ToString()) - decimal.Parse(NisVal.ToString())); //value gets assigned here
                }
            }
            catch(Exception ex)
            {
                var exceptionDialog = new MessageDialog
                {
                    Message = { Text = ex.ToString() }
                };

                await DialogHost.Show(exceptionDialog, "RootDialog");
            }
        }

    }
}

Databinding for Amount:

<TextBlock Foreground="Black" Margin="0 0 0 0" VerticalAlignment="Top" Grid.Column="3" Text="{Binding Path=Amount, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>

All the calculations that you see, work correctly and all values pass over to the View perfectly. However when I try saving, I get an Object Reference not set to instance of an object Exception.

How can I retrieve the values from the view for saving to database?

Edit: Ok so I've updated the code to make it more understandable. I receive the error in this line MessageBox.Show(StautoryIncome.ToString());. It holds the value after it's calculated in the CalcNis() method and performs other calculations with that same value. However, as soon as I try saving, it's like StautoryIncome returns 0 and any of the databindings returns the NullPointerException. Binding for Amount works perfectly, as soon as I start entering text in a Textbox, the TextBlock updates with same value.

bruh1234
  • 67
  • 8
  • you need to debug it, visual studio will tell you what is null – Keith Nicholas Feb 08 '17 at 02:47
  • You need to show the view for us to see what is happening, but you have an object==null in there somewhere. Would also help to highlight the exact line where the debugger is reporting a problem. – Kelly Feb 08 '17 at 02:50
  • Could you provide a [minimal reproducible example](http://stackoverflow.com/help/mcve) that shows where your code goes wrong? – JSteward Feb 08 '17 at 02:52
  • It would help if you could point out at which line the exception occurs, so you can know what exactly is null, better yet would be @KeithNicholas's suggestion (in debugging mode you can use Breakpoints which help you check the values in any variables at any line). – Keyur PATEL Feb 08 '17 at 03:05
  • See marked duplicate for extensive advice on how to diagnose and fix code throwing this exception. If after carefully reviewing all of the advice and following it closely, you are still unable to figure out your problem, post a new question in which you include a good [mcve] that reliably reproduces the problem and a clear, detailed explanation of what you've tried to diagnose the problem and what _specifically_ you are still having trouble with. – Peter Duniho Feb 08 '17 at 03:23
  • @KeithNicholas I've narrowed down my code to only the exact issues. The `Amount` property isn't the only one giving that error but if I can resolve that, then I'll be able to resolve the others also. Thanks for any help :) – bruh1234 Feb 08 '17 at 14:30
  • @Kelly I've updated my question, thanks for any help :) – bruh1234 Feb 08 '17 at 14:30
  • @JSteward I've updated the question – bruh1234 Feb 08 '17 at 14:31
  • You get a null ref on Amount becuase Amount is a string and is defualted to null, when you try to set the value you check `if (amount == string.Empty)` which it does not, it's null. (1) Initialize Amount to `string.Empty` or (2) `If (string.IsNullOrEmpty(Amount))` or (3) set its data type appropriately, maybe currency. – JSteward Feb 08 '17 at 14:46
  • @JSteward I changed Amount to decimal and now it's returning 0. I need it to return whatever value I enter into the Textbox and is displayed in a TextBlock. – bruh1234 Feb 08 '17 at 15:09
  • That sounds like a binding issue now. Your best bet is to post a new question with all the relevant bindings and we can help you better from there. – JSteward Feb 08 '17 at 15:11
  • Your bindings are wrong. I'd suggest grabbing Snoop and examining them at runtime. –  Feb 08 '17 at 15:32
  • @JSteward Okay I'll go ahead and post a new one. Just to make sure, I don't have to show all my bindings right? I can show one and if it's solved then I can do the same for the others? – bruh1234 Feb 08 '17 at 15:41
  • Yes, just the important ones. :) Sounds like the relevant ones would be anything that is or should be using Amount as a backing. Probably the `TextBlock` binding you've already posted and the binding for the `TextBox` – JSteward Feb 08 '17 at 15:45
  • @JSteward Okay, I've posted the question http://stackoverflow.com/questions/42117670/wpf-unable-to-retrieve-binding-values-mvvm Thanks for helping :) – bruh1234 Feb 08 '17 at 15:51

1 Answers1

0

The issue with this turned out to be that the UserControls weren't using the same instance of the ViewModel. The discussion was moved to: Unable to retrieve binding values MVVM, where it was solved :). Hope someone finds it useful.

Community
  • 1
  • 1
bruh1234
  • 67
  • 8