I have the following code in my windows 8 desktop app. This gets data from a web service and populates it in a List SampleDataGroup
.
protected override async void LoadState(Object navigationParameter, Dictionary<String, Object> pageState)
{
HttpClient client = new HttpClient();
HttpResponseMessage response = await client.GetAsync("http://localhost:12345/api/items");
var info = new List<SampleDataGroup>();
if (response.IsSuccessStatusCode)
{
var content = await response.Content.ReadAsStringAsync();
var item = JsonConvert.DeserializeObject<dynamic>(content);
foreach (var data in item)
{
var infoSect = new SampleDataGroup
(
(string)data.Id.ToString(),
(string)data.Name,
(string)"",
(string)data.PhotoUrl,
(string)data.Description
);
info.Add(infoSect);
//data=infoSect;
}
}
else
{
MessageDialog dlg = new MessageDialog("Error");
await dlg.ShowAsync();
}
}
This works fine. But I want to use the data in the above function in another function. I want to use. The properties and values I get from the web service, I would like to use in another function.
private void Item_Click(object sender, RoutedEventArgs e)
{
//Use (string)data.Name
}
In the click function I want to use the Name
, as well as all other data values from the first function.
I tried setting SampleDataGroup data=null;
in the code and then using data=infoSect
seen commented out above and then call data.Name in the click function but it returns an null exception.
How do i pass data from one function to another?
Well currently your async method returns void, and you're not doing anything with info
after populating it. It seems to me that you probably want to either return that list from the method (making it return Task<List<SampleDataGroup>>
for example) or make the method set the state in an instance variable, so that it becomes part of the state of the object the method is called on.
Without more information about the class you're designing, it's hard to know whether the information is logically part of the state of the object or whether it should be returned from the method - but those are your basic choices. (There are more complicated alternatives, but those are the first two to consider.)
You should also consider what you want to happen in terms of state if there's an error - you're showing a dialog box, but what do you want to happen after that?
See more on this question at Stackoverflow