LongListSelector.SelectedItem can't cast to my object class - c#

I have a LongListSelector that is populated with List which contains objects from SQLite database:
protected override async void OnNavigatedTo(NavigationEventArgs e)
{
SQLiteAsyncConnection conn = new SQLiteAsyncConnection(DB_PATH);
var query = conn.Table<Prasanja>().Where(x => x.id == 3);
var result = await query.ToListAsync();
foreach (var item in result)
{
var query1 = conn.Table<Odgovori>()
.Where(y => y.Prasanja_id == item.id);
txtPrasanje.Text = item.Tekst;
var resultOdgovori = await query1.ToListAsync();
foreach (var itemOdgovor in resultOdgovori)
{
Lista.Add(itemOdgovor.Odgovor.ToString());
lstOdgovori.ItemsSource = Lista;
}
}
What I want is when one of the LongListSelector items is tapped that I get the specific object tapped, and have the ability to use that object properties.Here is my code:
private void lstOdgovori_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
LongListSelector selector = sender as LongListSelector;
if (selector == null)
return;
Odgovori odg = selector.SelectedItem as Odgovori;
if (odg == null)
return;
if(odg.Tocno==null)
MessageBox.Show("Try again");
else MessageBox.Show("True!!!");
}
The problem here is that my object odg from the class Odgovori returns null after executing this code. How can I fix this?

You are adding a string to Lista that is why your casting is not working. If you have overridden your ToString() method in your Odgovori class I believe that the LongListSelector will call that method if you just add the Odgovori object to Lista

Related

Google Places Autocomplete does not populate the address

I have an active Google Places autocomplete working with Xamarin Forms or Cross Platform. I have a working solution that auto populates the address when the user types in the address. My problem is when the user selects it from the list the address does not go to the search_bar.text… The search bar just remains with the text that was typed? how can I get the text when selected to populate in the search bar.
I am new to Xamarin forms and C#.
public Createbusinessaccount ()
{
InitializeComponent ();
search_bar.ApiKey = GooglePlacesApiKey;
search_bar.Type = PlaceType.Address;
search_bar.Components = new Components("country:us"); // Restrict results to Australia and New Zealand
search_bar.PlacesRetrieved += Search_Bar_PlacesRetrieved;
search_bar.TextChanged += Search_Bar_TextChanged;
search_bar.MinimumSearchText = 2;
results_list.ItemSelected += Results_List_ItemSelected;
}
void Search_Bar_PlacesRetrieved(object sender, AutoCompleteResult result)
{
results_list.ItemsSource = result.AutoCompletePlaces;
spinner.IsRunning = false;
spinner.IsVisible = false;
if (result.AutoCompletePlaces != null && result.AutoCompletePlaces.Count > 0)
results_list.IsVisible = true;
}
void Search_Bar_TextChanged(object sender, TextChangedEventArgs e)
{
if (!string.IsNullOrEmpty(e.NewTextValue))
{
results_list.IsVisible = false;
spinner.IsVisible = true;
spinner.IsRunning = true;
}
else
{
results_list.IsVisible = true;
spinner.IsRunning = false;
spinner.IsVisible = false;
}
}
async void Results_List_ItemSelected(object sender, SelectedItemChangedEventArgs e)
{
if (e.SelectedItem == null)
return;
var prediction = (AutoCompletePrediction)e.SelectedItem;
results_list.SelectedItem = null;
var place = await Places.GetPlace(prediction.Place_ID, GooglePlacesApiKey);
if (place != null)
await DisplayAlert(
place.Name, string.Format("Lat: {0}\nLon: {1}", place.Latitude, place.Longitude), "OK");
}
In your ItemSelected method, you need to set the text of the searchbar:
async void Results_List_ItemSelected(object sender, SelectedItemChangedEventArgs e)
{
if (e.SelectedItem == null)
return;
var prediction = (AutoCompletePrediction)e.SelectedItem;
search_bar.Text = prediction.Name? // Your property here
results_list.SelectedItem = null;
var place = await Places.GetPlace(prediction.Place_ID, GooglePlacesApiKey);
if (place != null)
await DisplayAlert(
place.Name, string.Format("Lat: {0}\nLon: {1}", place.Latitude, place.Longitude), "OK");
}
I am still trying to fix this, it only adds the street name and number not the whole address

Why do you close the app when I change the page?

I have two List <>.
List<Musei> ListMusei;
List<Regioni> reg;
the object "Musei" has the property "Paese", while the object "Regioni" has the property "NomeProvincia".
The List "reg" is inserted in a ListView, and when pressed on an item, this method is invoked:
private void Listviewcitt_ItemClick(object sender, ItemClickEventArgs e)
{
var result = ((Regioni)e.ClickedItem).NomeProvincia.ToString();
var filtro = ListMusei.Where(x => x.Paese.Equals(result));
try
{
Frame.Navigate(typeof(PageAroundMe), filtro);
}
catch(Exception)
{
}
}
application where I always closes. I thought there was some problem in the "AroundMe", and then paste the code here:
In Page AroundMe I do this:
List<Musei> ListMusei;
protected async override void OnNavigatedTo(NavigationEventArgs e)
{
ListMusei = (List<Musei>) e.Parameter;
List<Pushpin> push = new List<Pushpin>();
foreach (Musei SingoloMuseo in ListMusei)
{
Pushpin Pushpin pushpin1 = new ();
GeoPoint posizioneP;
try
{
MapLocationFinderResult result = await MapLocationFinder.FindLocationsAsync (SingoloMuseo.Indirizzo, null);
posizioneP result.Locations.FirstOrDefault = ().Point;
pushpin1.Name = SingoloMuseo.NomeMuseo;
pushpin1.Location = posizioneP;
push.Add (pushpin1);
}
catch (Exception)
{
continue;
}
}
Where is the problem? I can not even figure out where I will close
You can pass the parameter like
Frame.Navigate(typeof(PageAroundMe), filtro.ToList());
The invalid cast exception occurs because you are trying to cast IEnumerable type to List.

display details using entity framework

I want to display details of a selected item from a combo box in wpf using entity framework. But my code below only displays the first entry from database no matter what item is selected.
private void ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
using (Entities c = new Entities())
{
string sFirst = c.UserProfiles.FirstOrDefault().First.ToString();
string sLast = c.UserProfiles.FirstOrDefault().Last.ToString();
txtFirst.Text = sFirst;
txtSecond.Text = sLast;
}
}
I think you are mixing up stuffs.
I believe what you actually want is the item within the combox.
Try this code:
private void ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
var comboBox = sender as ComboBox;
if (comboBox != null)
{
var item = comboBox.SelectedItem as EntityType;
//EntityType == the table you are loading into combobox (I guess it supposed to be UserProfile)
if (item != null)
{
txtFirst.Text = item.First.ToString();
txtSecond.Text = item.Last.ToString();
}
}
}
You are not filtering the data from the database... there is no where clause that specifies the selected item. I have no idea on the structure of your data but try something like this:
using (Entities c = new Entities())
{
string sFirst = c.UserProfiles.Where(u => u.Id == selectedItemId).First().First.ToString();
string sLast = c.UserProfiles.Where(u => u.Id == selectedItemId).First().Last.ToString();
txtFirst.Text = sFirst;
txtSecond.Text = sLast;
}
Furthermore, there is no point in using FirstOrDefault() if you are not going to check whether the result is null or not.

Update line in database

I'm developping an application with c# and ADO .NET entity data model. I have a table Articles(idArticle, nameArticle, statusArticles). I want to retrieve the first article where statusArticle=false, and update her value to true. Someone can help me with this code please:
private void button_Click(object sender, EventArgs e)
{
using (DbEntities db = new DbEntities())
{
Articles firstArticle = db.Articles.FirstOrDefault(u => u.statusArticle == false);
if (firstArticle != null)
{
firstArticle.statusArticle = true;
MessageBox.Show("Article validated", "OK");
this.Refresh();
}
}
}
This can be done as follows
private void button_Click(object sender, EventArgs e)
{
using (DbEntities db = new DbEntities())
{
Articles firstArticle = db.Articles.FirstOrDefault(u => u.statusArticle == false);
// firstArticle is not null anyways as you are calling FirstOrDefault()
**EDIT** // In case nothing has status = false, you will get a new Articles object, so instead of the below null check, you have to check for other property like id or name that will be unique.
if (firstArticle != null)
{
firstArticle.statusArticle = true;
db.SaveChanges();
MessageBox.Show("Article validated", "OK");
this.Refresh();
}
}
}
.FirstOrDefault()
public static TSource FirstOrDefault<TSource>(
this IEnumerable<TSource> source //db.Articles
)
will return:
default(TSource) if source is empty; otherwise, the first element in source.
default(TSource) returns null for reference type elements or (usually) 0 for value type elements.
Your amended code:
private void button_Click(object sender, EventArgs e)
{
using (DbEntities db = new DbEntities())
{
Articles firstArticle = db.Articles.FirstOrDefault(u => u.statusArticle == false);
if (firstArticle != null)
{
firstArticle.statusArticle = true;
MessageBox.Show("Article validated", "OK");
db.SaveChanges(); //change (can go before/after validation message)
this.Refresh();
}
}
}

Problems submitting DataGridView changes with Linq-to-SQL

I'm trying to implement database value edition through a DataGridView control but honestly I'm having a hard time trying to accomplish that. I'm basically using LINQ-to-SQL classes and events, the following being the most significant snippets:
var data = from q in data.FOOBARS
select new
{
ID = q.FOOBAR_ID,
LOREM = q.FOOBAR_LOREM,
IPSUM = q.FOOBAR_IPSUM
};
DataGridView grid = new DataGridView();
grid.DataSource = data;
// grid EVENTS
private void grid_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
{
this.grid.CurrentCell.ReadOnly = false;
this.grid.BeginEdit(true);
}
private void grid_CellLeave(object sender, DataGridViewCellEventArgs e)
{
if (this.grid.CurrentCell.IsInEditMode)
{
// METHOD CALL
this.SetVariableValue(this.grid.CurrentRow.Cells["ID"].Value.ToString(), this.grid.CurrentCell.OwningColumn.Name, this.grid.CurrentCell.FormattedValue.ToString(), this.grid.CurrentCell.EditedFormattedValue.ToString());
}
this.grid.CommitEdit(DataGridViewDataErrorContexts.Commit);
this.grid.EndEdit();
}
// METHOD IMPL
private void SetVariableValue(string id, string type, string current, string edited)
{
try
{
if (current != edited)
{
using (FOOBARDataClassesDataContext data = new FOOBARDataClassesDataContext(this.BuildConnection()))
{
data.ExecuteCommand("SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED");
switch (type)
{
case "LOREM":
var currentLorem = data.FOOBARS.SingleOrDefault(v => v.FOOBAR_ID == Convert.ToInt32(id)).FOOBAR_LOREM;
currentLorem = edited;
data.SubmitChanges(ConflictMode.ContinueOnConflict);
break;
case "IPSUM":
var currentIpsum = data.FOOBARS.SingleOrDefault(v => v.FOOBAR_ID == Convert.ToInt32(id)).FOOBAR_IPSUM;
currentIpsum = edited;
data.SubmitChanges(ConflictMode.ContinueOnConflict);
break;
default:
break;
}
data.Refresh(RefreshMode.OverwriteCurrentValues);
}
}
}
catch (Exception error)
{
if (logger.IsErrorEnabled) logger.Error(error.Message);
}
}
Debugging looks good, objects are actually being updated but for some reason changes are neither being submitted nor updated.
Any help would be certainly appreciated. Thanks much you guys in advance!
For some reason this does NOT WORK:
var currentLorem = data.FOOBARS.SingleOrDefault(v => v.FOOBAR_ID == Convert.ToInt32(id)).FOOBAR_LOREM;
currentLorem = edited;
data.SubmitChanges(ConflictMode.ContinueOnConflict);
But this DOES (notice the changes in lines 1 and 2, FOOBAR_LOREM attribute):
var currentLorem = data.FOOBARS.SingleOrDefault(v => v.FOOBAR_ID == Convert.ToInt32(id));
currentLorem.FOOBAR_LOREM = edited;
data.SubmitChanges(ConflictMode.ContinueOnConflict);

Categories