Master
Master

Reputation: 2163

Textbox Values Not Saving to Database

I'm currently doing a simple address binding and saving to Database, But when I click my save button, it does save but the textbox information is not saved. It just makes another address row full of nulls. I believe it has to do with the get;set; for the binded values. If anyone Could help me figure out why the Textbox values don't save please and thank you.

Xaml side:

<TextBox x:Name="Line1"  Text="{Binding SelectedAddress.Line1, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
<TextBox x:Name="City" Text="{Binding SelectedAddress.City, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />
<TextBox Text="{Binding SelectedAddress.PostalCode, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />

MVVM side:

public Address NewAddress { get; set; }
public string Line1 { get { return _address.Line1; } set { _address.Line1 = value; } }
public string City { get { return _address.City; } set { _address.City = value; } }
public string PostalCode{ get { return _address.PostalCode; } set { _address.PostalCode = value; } }

I've also Initiated:

public AddressViewModel(IEventAggregator events)
{
.....
_address = new Address(); 
}

Button action:

public void AddNewAddress()
{
    SelectedAddress = new Address();
    SelectedAddress.Line1 = _address.Line1;
    SelectedAddress.PostalCode = _address.PostalCode;
    SelectedAddress.City = _address.City;
    OnPropertyChanged("SelectedAddress");
    using (var ctx = DB.Get())
        {
            ctx.Addresses.Add(SelectedAddress);
            ctx.SaveChanges();
        }
}

I also Implemented OnPropertyChange from the previous post to "Notify" Binding a String to a richtextbox

Upvotes: 1

Views: 584

Answers (2)

MojAmiri
MojAmiri

Reputation: 526

Seems some mistakes there:

  • As Panagiotis said, there is no value for _address.
  • You should bind your context to your view (textboxes). If you're creating SelectedAddress just after button pressed, there is no relationship between data you entered in Textboxes and new SelectedAddress. You actually eliminate it.

Upvotes: 0

Panagiotis Kanavos
Panagiotis Kanavos

Reputation: 131748

Your controls bind to SelectedAddress yet AddNewAddress() effectively discards anything stored there and creates a new Address object with values from "somewhere". Since the _address field doesn't bind to anything, it will probably contain nulls.

The following code should work and save the values you have entered in the controls:

public void AddNewAddress()
{
    using (var ctx = DB.Get())
    {
        ctx.Addresses.Add(SelectedAddress);
        ctx.SaveChanges();
    }
    OnPropertyChanged("SelectedAddress");
}

Raising OnPropertyChanged is useful only if Address contains some auto-generated fields, eg an ID field that is set by the database. Otherwise, you can omit it entirely.

Upvotes: 1

Related Questions