Click here to Skip to main content
15,885,537 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a listview and a button which when clicked loads the listview with some items from an xml file. When the user clicks it again (because they might want to update the data in the listview to see if it has changed) it throws a NullReferenceException. Now I understand why this is thrown, it is because I am using this code to reload a listview after creating a list of items:
C#
// Remove and clear source [1]
timeSteps.ItemsSource = null;
timeSteps.Items.Clear();
// The list<> has been updated so reload the listview [2]
timeSteps.ItemsSource = timesteps;
// Select the first item and focus the control [3]
timeSteps.SelectedIndex = 0;
timeSteps.Focus();

I know that the error occurs at [1] because one of the items is selected and the SelectedItem property cannot be set to null so when the items are removed it throws an exception. How can I make is so the list can be reloadable when the user reclicks the button (otherwise they have to switch and go back to the page in the containing frame which works because all controls are reset so no exception is thrown. I don't really want to change the way I bind the items to the listview if I can help it but I can see why that might be the only option. The binding is a simple one:
XML
<ListView.View>
    <GridView>
        <GridViewColumn DisplayMemberBinding="{Binding TimeStepItem}" Header="Date" Width="135"/>
    </GridView>
</ListView.View>

C#
public class TimeStep
{
    public string TimeStepItem { get; set; }
    public string Link { get; set; }
}

With the usual list<> which I fill with TimeStepItems.
Posted
Comments
Member 14598472 7-Nov-19 2:14am    
But I Use
timeSteps.ItemsSource = null;
timeSteps.Items.Clear();

This Line And It's Working For Update Listview In Ui Side

1 solution

You are getting the exception here because you are making the itemsource to null and then trying to clear the items in it(rather it should be the opposite)

1. Use Observable Collection Which is meant for performing (Read,Update,Delete) operation dynamically to a collection

2.No need to make the itemsource to null, rather just clear the itemsource and re-assign with new values.

Improved Answer:

Try below code for using ObservableCollection in ListView

XML
private ObservableCollection<TimeStepData> timeStepDataCollection;
    public ObservableCollection<TimeStepData> TimeStepDataCollection
    {
        get
        {
            if (timeStepDataCollection== null)
            {
                timeStepDataCollection= new ObservableCollection<TimeStepData>();
            }
            return timeStepDataCollection;
        }
        set
        {
    timeStepDataCollection = value;
        }
    }

    //created a class for TimeStepData
    public  class TimeStepData
    {
        public string TimeStepItem1{ get; set; }
        public string TimeStepItem2{ get; set; }
        public string TimeStepItem3{ get; set; }
    }


// In XAML :

<ListView Height="96" Name="listView1" Width="226" ItemsSource="{Binding  TimeStepDataCollection}">
             <ListView.View>
              <GridView>
                <GridViewColumn Width="50" Header="Name"   DisplayMemberBinding="{Binding TimeStepItem1/>
                <GridViewColumn Width="70" Header="Class" DisplayMemberBinding="{Binding TimeStepItem2/>
                <GridViewColumn Width="70" Header="Status" DisplayMemberBinding="{Binding TimeStepItem3/>
              </GridView>
            </ListView.View>
       </ListView>
 
Share this answer
 
v4
Comments
Henry Hunt 29-Nov-13 14:54pm    
How would I implement the observable collection? I have looked on the internet for observable collections and listviews but cannot get anything to work
AnthonyMG 30-Nov-13 2:27am    
Henry, Check the solution provided
Henry Hunt 30-Nov-13 5:01am    
Does the XAML affect how the list reloads? Because I am still getting a NullReferenceException. I have pasted your C# code as it is without changing anything and am using this to control the items in it:

timeSteps.ItemsSource = null;
TimeStepDataCollection.Clear();

XmlDocument capabilities = new XmlDocument();
List<timestep> timesteps = new List<timestep>();
List<string> timeList = new List<string>();
List<timestep> reloading = new List<timestep>();

capabilities.Load(Data.MetOffice.DownloadXml(
"http://datapoint.metoffice.gov.uk/public/data/layer/wxobs/all/xml/capabilities?key=" +
UserProfile.Read.ApiKey(), DateTime.Now.Second.ToString()));

for (int x = 0; x < capabilities.SelectNodes("//Layer[@displayName='Rainfall']/Service/Times/Time").Count; x++)
{
timeList.Add(capabilities.SelectNodes("//Layer[@displayName='Rainfall']/Service/Times/Time")[x].InnerText);
}

foreach (string s in timeList)
{
TimeStepDataCollection.Add(new TimeStepData() {
TimeStepItem1 = (DateTime.Parse(s.Remove(10).Replace("-", "/")).ToString("dd/MM/yyyy") +
" at " + s.Remove(0, 11).Remove(5)) + ":00", TimeStepItem2 = s });
}
new Global().UpdateDataTree(set: "Observation Maps", entry: "Rainfall Rate",
step: timeList.ToArray(), type: "Observation", freq: "15 Minutes", dist:
"Met Office", serv: "OBSERVATION", unit: "mm/h (millimetres per hour)", key: "true");

timeSteps.ItemsSource = TimeStepDataCollection;

Maybe I am doing it wrong?
AnthonyMG 30-Nov-13 5:15am    
yes XAMl does have effect on each time your itemsource gets updated..

dont do this..clear your itemsource first and also why you need to make it NULL?.
timeSteps.ItemsSource = null;
TimeStepDataCollection.Clear();
Henry Hunt 30-Nov-13 7:26am    
I've got it, it works now. I had to do DataContext = this and a few other things when updating the listview so there are now no references to the listview control itself. Thank you!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900