My Code
Hello. I am using xamaring forms to create an app and I am having problems obtaining a certain value from an object.
Essentially I would like to take Address1 from the object e.SelectedItem and place it into a string called address. I plan to do this to all the variables in the object, so address, city, country, postal code, etc...
From here I will use these strings to form a url link that will take the user to their native map application with the address inputed into the url.
Note: The line of text I have var item = e.SelectedItem; was added for testing purposes.
Below I have some code:
async void AddressItemSelected(object sender, SelectedItemChangedEventArgs e)
{
if (e.SelectedItem != null)
{
var item = e.SelectedItem;
}
}
In summary: I would like to take the variables stored in an object and place them into their own string element.
Thank you!
you need to cast the object to the correct type first
var item = (MyClass)e.SelectedItem;
var addr1 = item.Address1
my suggestion would be cast your item NOT as "var", cast it as your exact class type.
Class item = (Class)e.selectedItem
Related
So I want to send two things in my pin when I push it to another page, the "Setbinding" works and the string (myString) gets pushed fine to the other page with the correct info. When I try to push my second string (mySecondString) through a setvalue/getvalue function i get the error: "Cannot convert method group expression to object." I have tried to use a string as well on the "Detailpage" but same error.
pin.SetBinding (Label.TextProperty, new Binding (myString));
pin.BindingContext = myString;
pin.SetValue (Label.TextProperty, mySecondString);
pin.GetValue (Label.TextProperty);
pin.Clicked += onButtonClicked1;
void onButtonClicked1 (object sender, EventArgs e)
{
Pin pin = (Pin)sender;
Navigation.PushAsync (new DetailPage (pin.SetValue, pin.BindingContext ));
}
public DetailPage (object info1, object info2)
Updated version:
pin.SetValue (Label.TextProperty, mySecondString);
new DetailPage (pin.GetValue(Label.TextProperty));
pin.SetValue is a method, so you need to use it as one (by adding brackets).
Also, I assume what you want to use is the getter, not the setter, as SetValue propably doesn't have a return value.
Try:
new DetailPage(pin.GetValue(), pin.BindingContext)
I am trying to find which item is selected in a ListView. When the selection is changed, I run the following code:
private void Change_CurrentConnection(object sender, SelectionChangedEventArgs e)
{
var d = e.AddedItems[0];
}
And you can see here what d is:
My question is, how can I access the Id, Name, and Url properties? (The properties are strings from a custom class. The ListView is bound to a collection of objects generated from that class.)
You need to cast the item as your class, which appears to be called Connection? You should first check to see if the object you are casting is actually of the type you wish to cast it to:
if (e.AddedItems[0] is Connection)
{
Connection toAccess = e.AddedItems[0] as Connection;
// Here you can access the properties directly
string myUrl = toAccess.Url;
}
This way we avoid an InvalidCastException.
you can do this as the following also
Connection lstViewItem = (Connection)YourListView.SelectedItems[0];
I have a LongListSelector with items. I made a contextMenu, so when you hold an item for some time you get an option to "pin to start". I didn't have a problem with binding the right item "name" and tile picture, but I have a problem with opening the right item than (or opening in general).
This is the code to pin the item to start:
private void Pin_click(object sender, RoutedEventArgs e)
{
PhoneApplicationService.Current.State["country"] = countriesList.SelectedItem;
Country selectedCountry = (sender as MenuItem).DataContext as Country;
string page = "/countryPage.xaml?id=" + countriesList.SelectedItem;
StandardTileData tileInfo = new StandardTileData
{
BackgroundImage = new Uri(selectedCountry.Flag, UriKind.Relative),
Title = selectedCountry.Name
};
ShellTile.Create(new Uri(page, UriKind.Relative), tileInfo);
}
The problem is on the countryPage, because there is no data context and the app crashes:
protected override void OnNavigatedTo(NavigationEventArgs e)
{
var k = (app.MainPage.Country)PhoneApplicationService.Current.State["country"];
DataContext = k;
}
2 suggestions based on your code :
Is the itemSource for your LongListSelector a collection of Country objects ? Because on the second page, you are trying to typecast the state data into a country object. That might be a problem.
Secondly, try using IsolatedStorage instead of Phone State, as State is transient data, as in not guarrenteed to last forever.
Presumably, you have a list of Country objects somewhere that you are using to populate the ItemsSource of your countriesList LongListSelector. Why don't you keep that list defined publicly in your App.xaml.cs class and make sure it is populated when the application is started using Application_Launching().
public static List<Country> Countries { get; set; }
In your Country objects, define some kind of unique identifier property using something like a Guid.
Guid m_CountryID;
public Guid CountryID
{
get { return m_CountryID; }
set { m_CountryID = value; }
}
Populate it when you create your Country objects
Country.CountryID = new Guid()
In your Pin_click method, set the QueryString id parameter to your CountryID from above.
string page = "/countryPage.xaml?id=" + selectedCountry.CountryID.ToString();
Then, in the OnNavigatedTo method of your countryPage.xaml.cs pull the Guid from the id parameter of your QueryString to retrieve the given Country object.
protected override void OnNavigatedTo(NavigationEventArgs e)
{
string countryID = string.Empty;
NavigationContext.QueryString.TryGetValue("id", out countryID);
System.Diagnostics.Debug.WriteLine(string.Concat("URI: ", e.Uri.ToString(), " | CountryID: ", countryID));
if (!string.IsNullOrWhiteSpace(countryID))
{
Guid countryGuid = new Guid();
Guid.TryParse(countryID, out countryGuid);
Country country = App.Countries.Where(x => x.CountryID == countryGuid).Select(x => x).FirstOrDefault();
if (country != null)
{
// ***** BUILD YOUR PAGE AS NEEDED HERE *****
// TextBlock1.Text = country.Name;
}
}
}
Now that you have the chosen Country object, just build that page as you see fit using the information in it.
Of course, all of this presumes you are maintaining the state of your country list between application sessions. Typically you would just write the list to an XML file in your isolated storage. GeekChamp has a great list of articles to get you up and running with isolated storage.
http://www.geekchamp.com/tips/all-about-wp7-isolated-storage---read-and-save-xml-files
Although, you could do this without worrying about isolated storage. Just use fixed Guid values (not new Guid()) when creating the Country objects in your Countries list, or choose an integer type and always ensure that the same integer value is associated with each Country as you rebuild it each time the app starts.
I have been working on trying to understand ArrayList but I have run into a problem with the final part of my search function.
I have an array list set up to take data in from a StreamReader. The data consists of numerous properties to do with teams, such as their name and the image path to their logo.
I have then created a search that scans through the array list for a specific piece of string input through a textbox by the user.
I have then created an if statement to open up a new form if that search was returned true.
I would like the new form to load up each property of the team according to the data searched for. E.g if I searched for "Liverpool" it would then come up with the manager name, stadium name as well as the searched for name in the new form. I do not know how to do this.
The only tool that I can really think of to do this is the load.event procedure but I can not find a lot of information about linking it to an array list.
private void btn_Search_Click(object sender, EventArgs e)
{
foreach (Object obj in allTeams)
{
Team = (Team)obj;
if (team.teamName.ToUpper() == nameToMatch.ToUpper()) //case insensitive search.
{
FormTeam frmTeam = new FormTeam(Team); //windows form that displays team info.
frmTeam.Visible = true;
break;
}
}
}
above is my search function. (I have not used List<T> because it was required that everything must be stored in an ArrayList.)
Is what I am trying to achieve possible? And if so how?
Also, you may want to use Linq on your ArrayList
foreach(var team in allTeams.OfType<Team>())
{
if(team.TeamName.Equals(nameToMatch, StringComparison.InvariantCultureIgnoreCase))
{
frmTeam = new FormTeam(Team);
Aplication.Run(frmTeam); // or frmTeam.Show();
break;
}
}
Inside the Constructor of your TeamForm class you simply assign all Values from the Team- Object to the fields on the Form.
public FormTeam (Team team)
{
teamName.Text = team.TeamName; // label or something
teamPlayerCount.text = team.PlayerCount.ToString();
...
}
If you need to search on a string such as the teamName, it would be better to use something like a Dictionary<string,Team> rather than an Arraylist. Then you'd be able to do
Team t = dic[nameToMatch.ToUpper()];
where dic is the instance of Dictionary<string,Team> that contains all your teams.
First, you're missing a variable name there. I think you meant
foreach (Object obj in allTeams)
{
Team t = (Team)obj;
if (t.teamName.ToUpper() == nameToMatch.ToUpper()) //case insensitive search.
{
FormTeam frmTeam = new FormTeam(t); //windows form that displays team info.
frmTeam.Visible = true;
break;
}
}
But why not used a typed generic List, not have to do all this silly casting.
But your question is "how can I pass what I searched to the new form", correct? I'd change the constructor for FormTeam to something like FormTeam(Team t, string nameToMatch) and save the value locally in TeamForm so you can do highlighting or whatever.
I want to transfer all data from HomeAddressUC to PermanentAddressUC with checkBox SameAsPrevious
Each UserControl has same Type(AddressUserControl)
DataSource to Fill HomeAddressUC is code is like this
private void SetTabPageDetails(string tabPageName, CustomerDetails customerDetailsCache)
{
customerDetailsCache = // calling stored procedure
PermanentAddressUC.SetDetails(customerDetailsCache.Addresses[0]);
}
Scope of that DataSource is upto it method SetTabPageDetails() only
logic I was trying to implement is on checkbox changed event is
if (chkSameAsPervious.Checked)
{
foreach (var addressCtl in from Control ctl in this.ADDRESS_TAB.Controls select ctl as BankSys24.UI.UserControls.AddressUserControl)
{
if (addressCtl.GroupBoxText == "Mailing Address")
{
// want to do something here
}
}
}
I try to follow the relevant link
Best practice when you need two user controls (winforms) to communicate
it says to use the Third Common User Control a Container or interface
What is the optimized way to do it?
Why you need to different user controls for home and mailing address if all the fields same?
you can use one user control for both and create property for set the group name as "Home address" or "Mailing address"
You can have two public methods to set address fields by passing address object and get address object by reading fields of the form.
On check change event of the checkbox you can get address object by calling home address user control instant get address method and then you can set that details on mailing address user control instant by calling set address method by passing address object.
Possible Shortest Solution I Found is like this :
if (chkSameAsPervious.Checked)
{
MailingAddressUC.SetDetails(PermanentAddressUC.GetDetails() as BankSys24.DTO.Customer.Address);
}
where
public object GetDetails()
{
return new BankSys24.DTO.Customer.Address { //data };
}
and
public void SetDetails(object input)
{
//intermediate Object
if (details != null)
{
//Mapping
}
Getdetails maps the all data as Container Class Object which can be Directly pass to SetDetails() ...