简体   繁体   中英

I cannot add an element to list property. VS says, that there is not set reference to an instance of an object

I'm trying to add an element from entry to a list property in viewmodel, using button. The viewmodel file is imported correctly (It whispers me the properties). I know, that there is some simple mistake, but I didn't figure it out.

//View part

//using the file with vm classes
using Pichacka.ViewModel;

//making an instance
viewmodel vm = new viewmodel();

private void BtnAddCertainFirm_Clicked(object sender, EventArgs e)
{
   if (String.IsNullOrWhiteSpace(entFirmName.Text) || String.IsNullOrWhiteSpace(entFirmMoney.
   {
      App.Current.MainPage.DisplayAlert("ERROR", "Nezadal jste všechny hodnoty!", "OK");
   }
   else
   {            
       string jmenoFirmy = entFirmName.Text; //getting the string value from entry
       //string penizeFirmy = entFirmMoney.Text; this line is not importatnt for this problem

       vm.listFirem.Add(jmenoFirmy); //here im trying to add an element
   }
}

//ViewModel part


//list property itself..
private List<string> _listFirem;

public List<string> listFirem
{
   get { return _listFirem; }
   set { _listFirem = value; }
}

Expected results: Clicking the button will add new element into the list property

Actual results: System.NullReferenceException: Object reference not set to an instance of an object.

You have created an instance of viewmodel only and not of listFirem property. Its default value will be null when you create an instance of viewmodel . Therefore when you try to add an element to this list, you will get the null reference exception.

To resolve this, initialize the listFirem property with an instance of List<string> . Like this:

viewmodel vm = new viewmodel();
vm.listFirem = new List<string>();

Yes,as akg179's reply, you'll need to ensure that the collection isn't null and is properly instantiated prior to adding an object to it.

public partial class Page5 : ContentPage
{

    public Page5 ()
    {
        InitializeComponent ();
    }
    viewmodel vm = new viewmodel();
    private void Btn1_Clicked(object sender, EventArgs e)
    {
        vm.listfirm = new List<string>();

        vm.listfirm.Add("test");
    }
}
public class viewmodel
{
    public List<string> listfirm { get; set; }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM