I want to delete the row by its Id but I cant delete it by its Id.like for example the values are
date|time|Floor|zone|Latitude|longitude and I want to delete a row of its while selecting it but i cannot.below is the class where i wrote all main functions
public class DbHelper
{
SQLiteConnection dbConn;
public async Task<bool> onCreate(string DB_PATH)
{
try
{
if (!CheckFileExists(DB_PATH).Result)
{
using (dbConn = new SQLiteConnection(DB_PATH))
{
dbConn.CreateTable<historyTableSQlite>();
}
}
return true;
}
catch
{
return false;
}
}
private async Task<bool> CheckFileExists(string fileName)
{
try
{
var store = await Windows.Storage.ApplicationData.Current.LocalFolder.GetFileAsync(fileName);
return true;
}
catch
{
return false;
}
}
//retrieve all list from the database
public ObservableCollection<historyTableSQlite> ReadHistory()
{
using (var dbConn = new SQLiteConnection(App.DB_PATH))
{
List<historyTableSQlite> myCollection = dbConn.Table<historyTableSQlite>().ToList<historyTableSQlite>();
ObservableCollection<historyTableSQlite> HistoryList = new ObservableCollection<historyTableSQlite>(myCollection);
return HistoryList;
}
}
// Insert the new info in the histrorytablesqlite table.
public void Insert(historyTableSQlite newcontact)
{
using (var dbConn = new SQLiteConnection(App.DB_PATH))
{
dbConn.RunInTransaction(() =>
{
dbConn.Insert(newcontact);
});
}
}
public void AddInfo()
{
//string f = Checkin.Floor_st;
Debug.WriteLine(Checkin.a);
string z = Checkin.Zone_st;
DbHelper Db_helper = new DbHelper();
Db_helper.Insert((new historyTableSQlite
{
Date = DateTime.Now.ToShortDateString(),
Time = DateTime.Now.ToShortTimeString(),
Zone = "D",
Floor = "7",
latitude =12344.66,
longtitude = -122.56
}));
}
// Delete specific contact
public void DeleteContact(int Id)
{
using (var dbConn = new SQLiteConnection(App.DB_PATH))
{
var existingvalue = dbConn.Query<historyTableSQlite>("select * from historyTableSQlite where Id =" + Id).FirstOrDefault();
if (existingvalue != null)
{
dbConn.RunInTransaction(() =>
{
dbConn.Delete(existingvalue);
});
}
}
}
//Delete all contactlist or delete Contacts table
public void DeleteAllContact()
{
using (var dbConn = new SQLiteConnection(App.DB_PATH))
{
//dbConn.RunInTransaction(() =>
// {
dbConn.DropTable<historyTableSQlite>();
dbConn.CreateTable<historyTableSQlite>();
dbConn.Dispose();
dbConn.Close();
//});
}
}
}
below is the class where I show the values
public partial class History : PhoneApplicationPage
{
ObservableCollection<historyTableSQlite> DB_HistoryList = new ObservableCollection<historyTableSQlite>();
DbHelper Db_helper = new DbHelper();
//int Selected_HistoryId;
public static int Selected_HistoryId { get; set; }
// string dbPath = Path.Combine(Windows.Storage.ApplicationData.Current.LocalFolder.Path, "db.sqlite");
public History()
{
InitializeComponent();
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
Db_helper.AddInfo();
ReadHistoryList_Loaded();
// Selected_HistoryId = int.Parse(NavigationContext.QueryString["SelectedHistoryID"]);
}
public void ReadHistoryList_Loaded()
{
ReadAllContactsList dbhistory = new ReadAllContactsList();
DB_HistoryList = dbhistory.GetAllHistory();//Get all DB contacts
ListData.ItemsSource = DB_HistoryList.OrderByDescending(i => i.Id).ToList();
//Latest contact ID can Display first
}
public void ListData_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (ListData.SelectedIndex != -1)
{
historyTableSQlite listitem = ListData.SelectedItem as historyTableSQlite;
int Selected_HistoryId = listitem.Id;
}
}
public void Delete_Click(object sender, EventArgs e)
{
Db_helper.DeleteContact(Selected_HistoryId);
}
private void DeleteAll_Click(object sender, EventArgs e)
{
DbHelper Db_helper = new DbHelper();
Db_helper.DeleteAllContact();//delete all db
DB_HistoryList.Clear();
ListData.ItemsSource = DB_HistoryList;
}
//public void updateDB(string fl,string zo,double la, double lo)
//{
// using (var db = new SQLiteConnection(dbPath))
// {
// var existing = db.Query<historyTableSQlite>("select * from historyTableSQlite").FirstOrDefault();
// if (existing != null)
// {
// existing.Floor = fl;
// existing.Zone = zo;
// existing.latitude = la;
// existing.longtitude = lo;
// db.RunInTransaction(() =>
// {
// db.Update(existing);
// });
// }
// }
//}
//public void AddDb(string fl, string zo, double la, double lo)
//{
// string dbPath = Path.Combine(Windows.Storage.ApplicationData.Current.LocalFolder.Path, "db.sqlite");
// using (var db = new SQLiteConnection(dbPath))
// {
// db.RunInTransaction(() =>
// {
// db.Insert(new historyTableSQlite()
// {
// Date = DateTime.Today.ToShortDateString(),
// Time = DateTime.Now.ToShortTimeString(),
// Floor = fl,
// Zone = zo,
// longtitude = la,
// latitude = lo
// });
// Debug.WriteLine(db);
// });
// }
}
I am updating the table class so that it is easy to understand
public class historyTableSQlite : INotifyPropertyChanged
{
[SQLite.PrimaryKey, SQLite.AutoIncrement]
public int Id { get; set; }
private int idvalue;
private string dateValue = string.Empty;
public string Date {
get { return this.dateValue; }
set
{
if (value != this.dateValue)
{
this.dateValue = value;
NotifyPropertyChanged("Date");
}
}
}
private string timeValue = string.Empty;
public string Time
{
get { return this.timeValue; }
set
{
if (value != this.timeValue)
{
this.timeValue = value;
NotifyPropertyChanged("Time");
}
}
}
private string floorValue = string.Empty;
public string Floor
{
get { return this.floorValue; }
set
{
if (value != this.floorValue)
{
this.floorValue = value;
NotifyPropertyChanged("Floor");
}
}
}
public string zoneValue;
public string Zone
{
get { return this.zoneValue; }
set
{
if (value != this.zoneValue)
{
this.zoneValue = value;
NotifyPropertyChanged("Zone");
}
}
}
private double latValue;
public double latitude
{
get { return latValue; }
set
{
if (value != this.latValue)
{
this.latValue = value;
NotifyPropertyChanged("Latitude");
}
}
}
private double lonValue;
public double longtitude
{
get { return this.lonValue; }
set
{
if (value != this.lonValue)
{
this.lonValue = value;
NotifyPropertyChanged("Longitude");
}
}
}
// public string isMarkPoint { get; set; }
public historyTableSQlite()
{
}
public historyTableSQlite(string date,string time,string floor,string zone,double lat,double lng)
{
Date = date;
Time = time;
Floor = floor;
Zone = zone;
latitude = lat;
longtitude = lng;
}
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(String info)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(info));
}
}
}
when i click the delete i.e the method delete_click i cant delete the row
EDIT: I cut and pasted your code incorrectly...you have very poor alignment :)
Okay I think I finally got your code to run, your problem is here
public void ListData_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (ListData.SelectedIndex != -1)
{
historyTableSQlite listitem = ListData.SelectedItem as historyTableSQlite;
// this will get destroy when the function exits, it's local decalartion
int Selected_HistoryId = listitem.Id;
// History.Selected_HistoryId = listitem.Id;
// you need to set the Property not a local variable
}
}
you made a local variable named the same as the Property it should be
History.Selected_HistoryId = listitem.Id;
public void Delete_Click(object sender, EventArgs e)
{
Db_helper.DeleteContact(History.Selected_HistoryId);
}
Related
Hello someone could help me please, I am making an application in Xamarin android as a project at school, but I have doubts with a checkbox and RecyclerView, what happens is that it assumes that the user can select one or more item within the RecyclerView and when push a poton that btnagregar save all the item name having the Checked property to true in a mysql database
MenuItemA.cs
RecyclerView mRecyclerView;
RecyclerView.LayoutManager mLayoutManager;
RecycleAdapter mAdapter;
List<ItemAli> alilist;
protected override void OnCreate(Bundle bundle)
{
base.OnCreate (bundle);
new I18N.West.CP1250();
new I18N.CJK.CP50220();
int idC = Convert.ToInt32(Intent.GetStringExtra("idc") ?? "Data not available");
SetContentView(Resource.Layout.RecyclerItem);
alilist = new List<ItemAli>();
try
{
string connsqlstring = "";
MySqlConnection sqlconn = new MySqlConnection(connsqlstring);
sqlconn.Open();
DataSet ds = new DataSet();
string queryString = "SELECT `IdAli`, `NombreA`, `Precio`, `Imagen`, `Tiempo` FROM `alimentos` as Item WHERE `IdCategoria` = " + idC;
MySqlDataAdapter adapter = new MySqlDataAdapter(queryString, sqlconn);
adapter.Fill(ds, "Item");
foreach (DataRow row in ds.Tables["Item"].Rows)
{
alilist.Add(new ItemAli { AliID = (row[0]).ToString(), Name = row[1].ToString(), Quantity = 0, Price = Convert.ToDecimal(row[2]), ImageId = row[3].ToString(), Time = row[4].ToString(), AddToOrder = false});
}
sqlconn.Close();
}
catch
{
Toast.MakeText(this, "La categoria esta vacia", ToastLength.Short).Show();
}
Button btnagregar = FindViewById<Button>(Resource.Id.btanadir);
mRecyclerView = FindViewById<RecyclerView>(Resource.Id.rvitem);
mLayoutManager = new LinearLayoutManager(this);
mRecyclerView.SetLayoutManager(mLayoutManager);
mAdapter = new RecycleAdapter(this,alilist);
mAdapter.ItemClick += OnItemClick;
mAdapter.SpinnerItemSelectionChanged += SpinnerItemSelectionChangedEvent;
mRecyclerView.SetAdapter(mAdapter);
btnagregar.Click += delegate
{
};
}
void OnItemClick(object sender, string IdAlimento)
{
var a = new Intent(this, typeof(ActividadDetAli));
a.PutExtra("idA", IdAlimento);
StartActivity(a);
}
void SpinnerItemSelectionChangedEvent(object sender, AdapterView.ItemSelectedEventArgs e)
{
Spinner spinner = (Spinner)sender;
var itemPosition = Convert.ToInt32 (spinner.Tag);
var currentquantity = alilist[itemPosition].Quantity;
var selectedQuantity = Convert.ToInt32( spinner.GetItemAtPosition (e.Position).ToString());
if (currentquantity != selectedQuantity) {
alilist [itemPosition].Quantity = selectedQuantity;
mAdapter.NotifyItemChanged (itemPosition);
}
}
}
RecycleAdapter.cs
public class VegeViewHolder: RecyclerView.ViewHolder
{
public ImageView Image { get; set; }
public TextView Name { get; set; }
public Spinner Quantity { get; set; }
public TextView Price { get; set; }
public TextView TotalAmount { get; set; }
public CheckBox cbx { get; set; }
public string idA { get; set; }
public VegeViewHolder(View itemView, Action<string> itemlistner, Action<object,AdapterView.ItemSelectedEventArgs> spinnerItemSelected )
:base(itemView)
{
Image = itemView.FindViewById<ImageView> (Resource.Id.list_image);
Name = itemView.FindViewById<TextView> (Resource.Id.Name);
Price = itemView.FindViewById<TextView> (Resource.Id.Price);
Quantity = itemView.FindViewById<Spinner> (Resource.Id.spinner1);
TotalAmount = itemView.FindViewById<TextView> (Resource.Id.total);
cbx = itemView.FindViewById<CheckBox>(Resource.Id.cbc);
itemView.Click += (sender, e) => itemlistner (idA);
Quantity.ItemSelected+= new EventHandler<AdapterView.ItemSelectedEventArgs> (spinnerItemSelected);
}
}
public class RecycleAdapter:RecyclerView.Adapter
{
public event EventHandler<string> ItemClick;
public event EventHandler<AdapterView.ItemSelectedEventArgs> SpinnerItemSelectionChanged;
public List<ItemAli> Items;
Activity Context;
List<string> _quantity = new List<string> ();
public RecycleAdapter (Activity context, List<ItemAli> list)
{
this.Items = list;
this.Context = context;
PopulateSpinnerDropDownValues ();
}
void PopulateSpinnerDropDownValues()
{
_quantity.Add ("0");
_quantity.Add ("1");
_quantity.Add ("2");
_quantity.Add ("3");
_quantity.Add ("4");
_quantity.Add ("5");
_quantity.Add ("6");
_quantity.Add ("7");
_quantity.Add ("8");
_quantity.Add ("9");
_quantity.Add("10");
_quantity.Add("11");
_quantity.Add("12");
_quantity.Add("13");
_quantity.Add("14");
_quantity.Add("15");
}
public override RecyclerView.ViewHolder
OnCreateViewHolder(ViewGroup parent, int viewType)
{
View itemView = LayoutInflater.From(parent.Context).
Inflate(Resource.Layout.list_items, parent, false);
VegeViewHolder vh = new VegeViewHolder(itemView, OnClick,spinner_ItemSelected);
return vh;
}
public override int ItemCount
{
get { return Items != null ? Items.Count : 0; }
}
void OnClick(string IdAlimento)
{
if (ItemClick != null)
ItemClick (this, IdAlimento);
}
private void spinner_ItemSelected (object sender, AdapterView.ItemSelectedEventArgs e)
{
if (SpinnerItemSelectionChanged != null)
SpinnerItemSelectionChanged (sender, e);
}
public Bitmap GetBitmapFromUrl(string url)
{
using (WebClient webClient = new WebClient())
{
byte[] bytes = webClient.DownloadData(url);
if (bytes != null && bytes.Length > 0)
{
return BitmapFactory.DecodeByteArray(bytes, 0, bytes.Length);
}
}
return null;
}
public override void OnBindViewHolder(RecyclerView.ViewHolder viewHolder, int position)
{
var item = Items[position];
var vh = viewHolder as VegeViewHolder;
var spinnerPos = 0;
var adapter =new ArrayAdapter<String>(Context, Android.Resource.Layout.SimpleSpinnerItem, _quantity);
adapter.SetDropDownViewResource (Android.Resource.Layout.SimpleSpinnerDropDownItem);
vh.Name.Text = item.Name;
vh.Price.Text = string.Format("Precio: ${0}",item.Price);
vh.ItemView.Tag = position;
if (item.Quantity > 0) {
spinnerPos = adapter.GetPosition (item.Quantity.ToString ());
vh.TotalAmount.Text = string.Format ("${0}", item.Price * item.Quantity);
} else {
vh.TotalAmount.Text = "";
}
vh.Quantity.Tag = position;
vh.Quantity.Adapter = adapter;
vh.Quantity.SetSelection(spinnerPos);
Bitmap bitmap = GetBitmapFromUrl(item.ImageId);
vh.Image.SetImageBitmap(bitmap);
vh.idA = item.AliID +"°"+ item.ImageId + "°" + item.Name + "°" + item.Price + "°" + item.Time;
vh.cbx.Checked = item.AddToOrder;
}
}
}
I have a form with 2 combos, among other fields. 1 combo is filled with brand names (cmbMarca). This combo is filled correctly.
The other combo (cmbModelo) should be filled with models of the selected brand.
My problem is that the combo with models (cmbModelo) is not updated when selecting a brand (cmbBrand). When I select a brand, runs all the code but does not display any item in the combo "cmbModelo"
FillingForm.xaml
<Input:SfComboBox x:Name="cmbMarca" x:uid="BrandsCombo"
DisplayMemberPath="marca"
ItemsSource="{Binding MarcasSAT.Marcas}" SelectedValue="{Binding marca, Mode=TwoWay}"
SelectedValuePath="marca"
Tag="{Binding Path=SelectedMarca, Mode=TwoWay}" SelectionChanged="cmbMarca_SelectionChanged"/>
<Input:SfComboBox x:Name="cmbModelo" x:uid="ModelosCombo"
DisplayMemberPath="modelo"
ItemsSource="{Binding ModelosSAT.Modelos}"
SelectedValue="{Binding modelo, Mode=TwoWay}"
SelectedValuePath="modelo" />
FillingForm.CS
private void cmbMarca_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
MarcaViewModel curItem = (MarcaViewModel)cmbMarca.SelectedItem;
this.cmbMarca.Tag = curItem.idMarca;
}
FillingViewModel.cs
public class FillingViewModel : ViewModelBase
{
private readonly MarcasViewModel marcasSAT = new MarcasViewModel();
public MarcasViewModel MarcasSAT
{
get { return this.marcasSAT; }
}
private ModelosViewModel modelosSAT = new ModelosViewModel();
public ModelosViewModel ModelosSAT
{
get
{
return this.modelosSAT;
}
set
{
modelosSAT = value;
RaisePropertyChanged("ModelosSAT");
}
}
private int _selectedMarca;
public int SelectedMarca
{
get { return _selectedMarca; }
set
{
_selectedMarca = value;
RaisePropertyChanged("SelectedMarca");
modelosSAT.MarcaID = _selectedMarca;
}
}
}
ModelosViewModel.cs
public class ModelosViewModel : ViewModelBase
{
private ObservableCollection<ModeloViewModel> modelos;
public ObservableCollection<ModeloViewModel> Modelos
{
get
{
return modelos ;
}
set
{
modelos = value;
RaisePropertyChanged("Modelos");
}
}
public ObservableCollection<ModeloViewModel> GetModelos()
{
modelos = new ObservableCollection<ModeloViewModel>();
using (var db = new SQLite.SQLiteConnection(App.DBPath))
{
var query = db.Table<Modelos>().Where(c => c.idMarca == _marcaID);
//var query = db.Table<Modelos>();
foreach (var _mrc in query)
{
var mrc = new ModeloViewModel()
{
idMarca = _mrc.idMarca,
idModelo = _mrc.idModelo,
modelo = _mrc.modelo
};
modelos.Add(mrc);
}
}
return modelos ;
}
private int _marcaID=0;
public int MarcaID
{
get {
return _marcaID;
}
set
{
_marcaID = value;
RaisePropertyChanged("MarcaID");
this.GetModelos();
}
}
//public ModelosViewModel()
//{
// this.modelos = GetModelos();
//}
}
MarcasViewModel.cs
public class MarcasViewModel : ViewModelBase
{
private ObservableCollection<MarcaViewModel> marcas;
public ObservableCollection<MarcaViewModel> Marcas
{
get
{
return marcas ;
}
set
{
marcas = value;
RaisePropertyChanged("Marcas");
}
}
public ObservableCollection<MarcaViewModel> GetMarcas()
{
marcas = new ObservableCollection<MarcaViewModel>();
using (var db = new SQLite.SQLiteConnection(App.DBPath))
{
var query = db.Table<Marcas>();
foreach (var _mrc in query)
{
var mrc = new MarcaViewModel()
{
idMarca = _mrc.idMarca ,
marca = _mrc.marca
};
marcas.Add(mrc);
}
}
return marcas ;
}
public MarcasViewModel()
{
this.marcas = GetMarcas();
}
}
ViewModelBase.cs
public class ViewModelBase
{
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void RaisePropertyChanged(string propertyName)
{
var handler = this.PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
}
UPDATE1:
when I select a brand item, only the next code is called and in this order:
1st (in FillinfgForm.cs)
private void cmbMarca_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
MarcaViewModel curItem = (MarcaViewModel)cmbMarca.SelectedItem;
this.cmbMarca.Tag = curItem.idMarca;
}
2nd (in FillingViewModel.cs)
public int SelectedMarca
set
{
_selectedMarca = value;
RaisePropertyChanged("SelectedMarca");
modelosSAT.MarcaID = _selectedMarca;
}
3rd (in ModelosViewModel.cs)
Public int MarcaID
{
set
{
_marcaID = value;
RaisePropertyChanged("MarcaID");
this.GetModelos();
}
}
4th
public ObservableCollection<ModeloViewModel> GetModelos()
{
modelos = new ObservableCollection<ModeloViewModel>();
using (var db = new SQLite.SQLiteConnection(App.DBPath))
{
var query = db.Table<Modelos>().Where(c => c.idMarca == _marcaID);
//var query = db.Table<Modelos>();
foreach (var _mrc in query)
{
var mrc = new ModeloViewModel()
{
idMarca = _mrc.idMarca,
idModelo = _mrc.idModelo,
modelo = _mrc.modelo
};
modelos.Add(mrc);
}
}
return modelos ;
}
The problem is in GetMarcas() methods.
As you can see you work not with the property but with the field - 'marcas'. But when you assign a value to a field (in you particular case marcas = new ObservableCollection();) PropertyChanged method is not invoked. That is why you don't see UI changes.
You should work with the property istead of field or you can clear the existing ObservableCollection and add you values. Both variants should work.
So the following code should work:
public ObservableCollection<MarcaViewModel> GetMarcas()
{
Marcas = new ObservableCollection<MarcaViewModel>();
using (var db = new SQLite.SQLiteConnection(App.DBPath))
{
var query = db.Table<Marcas>();
foreach (var _mrc in query)
{
var mrc = new MarcaViewModel()
{
idMarca = _mrc.idMarca ,
marca = _mrc.marca
};
marcas.Add(mrc);
}
}
return marcas ;
}
or, a better solution:
public ObservableCollection<MarcaViewModel> GetMarcas()
{
Marcas.Clear();
using (var db = new SQLite.SQLiteConnection(App.DBPath))
{
var query = db.Table<Marcas>();
foreach (var _mrc in query)
{
var mrc = new MarcaViewModel()
{
idMarca = _mrc.idMarca ,
marca = _mrc.marca
};
Marcas.Add(mrc);
}
}
return marcas;
}
Also there is a good practice called "do not ignore return values", as you can see you don't need to return ObservableCollection from GetMarcas, so either rewrite it so that it returns nothing or rewrite invoking code (it dependes on your existing code).
I am developing an windows phone app using sqlite database.I am able to show out the database and delete the particular row I want to delete.But the problem is after I select the row and click delete the row does not vanishes at that time.I have to renter that page to see that it is deleted.
Below here is the code of the class where I use the click_delete event
public partial class History : PhoneApplicationPage
{
ObservableCollection<historyTableSQlite> DB_HistoryList = new ObservableCollection<historyTableSQlite>();
DbHelper Db_helper = new DbHelper();
//public static int Selected_HistoryId;
//int Selected_HistoryId;
public static int Selected_HistoryId {get; set;}
// string dbPath = Path.Combine(Windows.Storage.ApplicationData.Current.LocalFolder.Path, "db.sqlite");
public History()
{
InitializeComponent();
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
Db_helper.AddInfo();
ReadHistoryList_Loaded();
// Selected_HistoryId = int.Parse(NavigationContext.QueryString["SelectedHistoryID"]);
}
public void ReadHistoryList_Loaded()
{
ReadAllContactsList dbhistory = new ReadAllContactsList();
DB_HistoryList = dbhistory.GetAllHistory();//Get all DB contacts
ListData.ItemsSource = DB_HistoryList.OrderByDescending(i => i.Id).ToList();
//Latest contact ID can Display first
}
public void ListData_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (ListData.SelectedIndex != -1)
{
historyTableSQlite listitem = ListData.SelectedItem as historyTableSQlite;
History.Selected_HistoryId = listitem.Id;
}
}
private void Delete_Click(object sender, EventArgs e)
{
Db_helper.DeleteContact(History.Selected_HistoryId);
NavigationService.Navigate(new Uri("/History.xaml", UriKind.Relative));
}
private void DeleteAll_Click(object sender, EventArgs e)
{
DbHelper Db_helper = new DbHelper();
Db_helper.DeleteAllContact();//delete all DB contacts
DB_HistoryList.Clear();//Clear collections
ListData.ItemsSource = DB_HistoryList;
}
}
}
below is the class with all main functions
public class DbHelper
{
SQLiteConnection dbConn;
public async Task<bool> onCreate(string DB_PATH)
{
try
{
if (!CheckFileExists(DB_PATH).Result)
{
using (dbConn = new SQLiteConnection(DB_PATH))
{
dbConn.CreateTable<historyTableSQlite>();
}
}
return true;
}
catch
{
return false;
}
}
private async Task<bool> CheckFileExists(string fileName)
{
try
{
var store = await Windows.Storage.ApplicationData.Current.LocalFolder.GetFileAsync(fileName);
return true;
}
catch
{
return false;
}
}
//retrieve all list from the database
public ObservableCollection<historyTableSQlite> ReadHistory()
{
using (var dbConn = new SQLiteConnection(App.DB_PATH))
{
List<historyTableSQlite> myCollection = dbConn.Table<historyTableSQlite>().ToList<historyTableSQlite>();
ObservableCollection<historyTableSQlite> HistoryList = new ObservableCollection<historyTableSQlite>(myCollection);
return HistoryList;
}
}
// Insert the new info in the histrorytablesqlite table.
public void Insert(historyTableSQlite newcontact)
{
using (var dbConn = new SQLiteConnection(App.DB_PATH))
{
dbConn.RunInTransaction(() =>
{
dbConn.Insert(newcontact);
});
}
}
public void AddInfo()
{
DbHelper Db_helper = new DbHelper();
Db_helper.Insert((new historyTableSQlite
{
Date = DateTime.Now.ToShortDateString(),
Time = DateTime.Now.ToShortTimeString(),
Zone = Checkin.Zone_st,
Floor = Checkin.Floor_st,
latitude = Checkin.Latitud_do,
longtitude = Checkin.Longtitude_do
}));
}
// Delete specific contact
public void DeleteContact(int Id)
{
using (var dbConn = new SQLiteConnection(App.DB_PATH))
{
var existingvalue = dbConn.Query<historyTableSQlite>("select * from historyTableSQlite where Id =" + Id).FirstOrDefault();
if (existingvalue != null)
{
dbConn.RunInTransaction(() =>
{
dbConn.Delete(existingvalue);
});
}
}
}
//Delete all contactlist or delete Contacts table
public void DeleteAllContact()
{
using (var dbConn = new SQLiteConnection(App.DB_PATH))
{
//dbConn.RunInTransaction(() =>
// {
dbConn.DropTable<historyTableSQlite>();
dbConn.CreateTable<historyTableSQlite>();
dbConn.Dispose();
dbConn.Close();
//});
}
}
below is the class with all tables
public class historyTableSQlite : INotifyPropertyChanged
{
[SQLite.PrimaryKey, SQLite.AutoIncrement]
public int Id
{
get;
set;
}
private int idValue;
private string dateValue = string.Empty;
public string Date
{
get { return this.dateValue; }
set
{
if (value != this.dateValue)
{
this.dateValue = value;
NotifyPropertyChanged("Date");
}
}
}
private string timeValue = string.Empty;
public string Time
{
get { return this.timeValue; }
set
{
if (value != this.timeValue)
{
this.timeValue = value;
NotifyPropertyChanged("Time");
}
}
}
private string floorValue = string.Empty;
public string Floor
{
get { return this.floorValue; }
set
{
if (value != this.floorValue)
{
this.floorValue = value;
NotifyPropertyChanged("Floor");
}
}
}
public string zoneValue;
public string Zone
{
get { return this.zoneValue; }
set
{
if (value != this.zoneValue)
{
this.zoneValue = value;
NotifyPropertyChanged("Zone");
}
}
}
private double latValue;
public double latitude
{
get { return latValue; }
set
{
if (value != this.latValue)
{
this.latValue = value;
NotifyPropertyChanged("Latitude");
}
}
}
private double lonValue;
public double longtitude
{
get { return this.lonValue; }
set
{
if (value != this.lonValue)
{
this.lonValue = value;
NotifyPropertyChanged("Longitude");
}
}
}
// public string isMarkPoint { get; set; }
public historyTableSQlite()
{
}
public historyTableSQlite(string date, string time, string floor, string zone, double lat, double lng)
{
Date = date;
Time = time;
Floor = floor;
Zone = zone;
latitude = lat;
longtitude = lng;
}
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(String info)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(info));
}
}
}
If you delete the item from your ObservableCollection, it will notify the ListBox to update its container.
In your code you have
// this is correct
ObservableCollection<historyTableSQlite> DB_HistoryList = new ObservableCollection<historyTableSQlite>();
But your problem is that you don't actually link your ListBox to it.
In your code you create a copy (and the worst kind of copy given what you're trying to do) and you set the ListBox ItemsSource to it. See below (you have this)
ListData.ItemsSource = DB_HistoryList.OrderByDescending(i => i.Id).ToList();
So basically, your ListBox is not an ObservableCollection but it's a List structure.
Deleting and Inserting into the List will not update the ListBox's UI.
Get rid of this List, find another way to sort your ObservableCollection.
Then you can basically do this
ListData.ItemsSource = DB_HistoryList; // set the listbox to the actual obs collection
DB_HistoryList.RemoveAt(i); // remove the item at index i
DB_HistoryList.RemoveItem(object); // remove the object that matches
I'm trying to POST data to server and get the response to bind it to a Long List Selector. This is the code :
public class TestData
{
private string _LikeNum, _CommentNum, _HyperLinkTitle, _HyperLinkNavigationLink, _BrandImage, _PostImage, _PostDate, _PostTitle, _PostDescription, _PostID;
public string LikeNum { get { return _LikeNum; } set { _LikeNum = value; } }
public string CommentNum { get { return _CommentNum; } set { _CommentNum = value; } }
public string HyperLinkTitle { get { return _HyperLinkTitle; } set { _HyperLinkTitle = value; } }
public string HyperLinkNavigationLink { get { return _HyperLinkNavigationLink; } set { _HyperLinkNavigationLink = value; } }
public string BrandImage { get { return _BrandImage; } set { _BrandImage = value; } }
public string PostImage { get { return _PostImage; } set { _PostImage = value; } }
public string PostDate { get { return _PostDate; } set { _PostDate = value; } }
public string PostTitle { get { return _PostTitle; } set { _PostTitle = value; } }
public string PostDescription { get { return _PostDescription; } set { _PostDescription = value; } }
public string PostID { get { return _PostID; } set { _PostID = value; } }
public TestData(string LNum, string CNum, string HLTitle, string HLNaviagtionLink, string BImage, string PImage, string PDate, string PTitle, string PDescription, string PID)
{
this.LikeNum = LNum;
this.CommentNum = CNum;
this.HyperLinkTitle = HLTitle;
this.HyperLinkNavigationLink = HLNaviagtionLink;
this.BrandImage = BImage;
this.PostImage = PImage;
this.PostDate = PDate;
this.PostTitle = PTitle;
this.PostDescription = PDescription;
this.PostID = PID;
}
}
#region Lists of data
List<string> LstBrandID = new List<string>();
List<string> LstBrandName = new List<string>();
List<string> LstBrandLongitude = new List<string>();
List<string> LstBrandLatitude = new List<string>();
List<string> LstPostID = new List<string>();
List<string> LstPostTitle = new List<string>();
List<string> LstPostDescription = new List<string>();
List<string> LstPostDate = new List<string>();
List<string> LstLikeNum = new List<string>();
List<string> LstCommentNum = new List<string>();
List<string> LstUserLike = new List<string>();
List<string> LstCatName = new List<string>();
List<string> LstUserFollow = new List<string>();
#endregion
ObservableCollection<TestData> DataList = new ObservableCollection<TestData>();
string id;
public Home()
{
InitializeComponent();
id = PhoneApplicationService.Current.State["id"].ToString();
try
{
GetPosts(id);
myLLS.ItemsSource = DataList;
for (int i = 1; i <= 10; i++)
{
DataList.Add(new TestData(LstLikeNum[i], LstCommentNum[i], LstBrandName[i], "SomePage.xaml", "SomeLink.com/data/" + LstBrandID[i], "SomeLink.com/data/" + LstPostID[i], LstPostDate[i], LstPostTitle[i], LstPostDescription[i], LstPostID[i]));
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
throw;
}
}
#region getting data
void GetPosts(string UserID)
{
WebClient webclient = new WebClient();
Uri uristring = new Uri("SomeLink.com");
webclient.Headers["Content-Type"] = "application/x-www-form-urlencoded";
string postJsonData = string.Empty;
postJsonData += "userId=" + UserID;
webclient.UploadStringAsync(uristring, "POST", postJsonData);
webclient.UploadStringCompleted += webclient_UploadStringCompleted;
}
void webclient_UploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
{
try
{
if (e.Result != null)
{
string response = e.Result.ToString();
JArray a = JArray.Parse(response);
foreach (JObject o in a.Children<JObject>())
{
foreach (JProperty p in o.Properties())
{
string name = p.Name;
string value = p.Value.ToString();
if (name == "brandId")
{
LstBrandID.Add(value);
}
else if (name == "brandName")
{
LstBrandName.Add(value);
}
else if (name == "brandLongitude")
{
LstBrandLongitude.Add(value);
}
else if (name == "brandLatitude")
{
LstBrandLatitude.Add(value);
}
else if (name == "postId")
{
LstPostID.Add(value);
}
else if (name == "postTitle")
{
LstPostTitle.Add(value);
}
else if (name == "postDescription")
{
LstPostDescription.Add(value);
}
else if (name == "postDate")
{
LstPostDate.Add(value);
}
else if (name == "likeNum")
{
LstLikeNum.Add(value);
}
else if (name == "commentNum")
{
LstCommentNum.Add(value);
}
else if (name == "userLike")
{
LstUserLike.Add(value);
}
else if (name == "catName")
{
LstCatName.Add(value);
}
else if (name == "userFollow")
{
LstUserFollow.Add(value);
}
}
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
#endregion
When I run the application I get Out Of Range Exception
Getting data isn't the problem. The problem is the time it takes to get data from server to bind it to the Long List Selector. So, how can I delay the binding tell I get the data from the server and fill the Lists with them ?
In your Home():
myLLS.ItemsSource = DataList;
is good. You are telling your LLS to watch this data source and update itself whenever a new item is inserted.
for (int i = 1; i <= 10; i++)
{
DataList.Add(new TestData(LstLikeNum[i], LstCommentNum[i], LstBrandName ...);
}
is not good. You are trying to populate your data source before the data arrived. This is the operation that belongs in your request's callback. You're getting an out of range exception because LstLikeNum has 0 items, and you're trying to get items 0 -> 9.
Instead, do this:
void webclient_UploadStringCompleted(object sender, UploadStringCompletedEventArgs e) {
...
int i = 0;
foreach (JObject o in a.Children<JObject>())
{
foreach (JProperty p in o.Properties())
{
...
}
var testData = new TestData(LstLikeNum[i], LstCommentNum[i], ...);
DataList.Add(testData);
i++;
}
}
Note that you don't need to bind (myLLS.ItemsSource = DataList) in the callback. That's something you only do once -- the callback is only adding items to the source.
I am trying to build a combo list for a program to fill the combobox with a list of applications. it keeps throwing up "Cannot bind to the new display member. Parameter name: newDisplayMember"
private void BuildComboList()
{
Applicant defaultApplicant = new Applicant();
applicationList = defaultApplicant.GetList();
applicantList.DataSource = applicationList;
applicantList.DisplayMember = "DisplayName";
applicantList.ValueMember = "DisplayValue";
}
Applicant Class
public class Applicant
{
//Members
private int applicant_ID;
private string applicant_fname;
private string applicant_lname;
private string applicant_phone;
private string applicant_address1;
private string applicant_address2;
private string applicant_city;
private string applicant_state;
private string applicant_zip;
private string applicant_email;
//properties
public int Applicant_ID
{
get { return applicant_ID; }
set { applicant_ID = value; }
}
public string Applicant_fname
{
get { return applicant_fname; }
set { applicant_fname = value; }
}
public string Applicant_lname
{
get { return applicant_lname; }
set { applicant_lname = value; }
}
public string Applicant_phone
{
get { return applicant_phone; }
set { applicant_phone = value; }
}
public string Applicant_address1
{
get { return applicant_address1; }
set { applicant_address1 = value; }
}
public string Applicant_address2
{
get { return applicant_address2; }
set { applicant_address2 = value; }
}
public string Applicant_city
{
get { return applicant_city; }
set { applicant_city = value; }
}
public string Applicant_state
{
get { return applicant_state; }
set { applicant_state = value; }
}
public string Applicant_zip
{
get { return applicant_zip; }
set { applicant_zip = value; }
}
public string Applicant_email
{
get { return applicant_email; }
set { applicant_email = value; }
}
//Constructors
private void DefaultValues()
{
applicant_ID = 0;
applicant_fname = "";
applicant_lname = "";
applicant_phone = "";
applicant_address1 = "";
applicant_address2 = "";
applicant_city = "";
applicant_state = "";
applicant_zip = "";
applicant_email = "";
}
private void Rec2Members(ApplicantRecord record)//defined in ApplicantDL
{
applicant_ID = record.applicant_ID;
applicant_fname = record.applicant_fname;
applicant_lname = record.applicant_lname;
applicant_phone = record.applicant_phone;
applicant_address1 = record.applicant_address1;
applicant_address2 = record.applicant_address2;
applicant_city = record.applicant_city;
applicant_state = record.applicant_state;
applicant_zip = record.applicant_zip;
applicant_email = record.applicant_email;
}
public ApplicantRecord ToRecord()
{
ApplicantRecord record = new ApplicantRecord();
record.applicant_ID = applicant_ID;
record.applicant_fname = applicant_fname;
record.applicant_lname = applicant_lname;
record.applicant_phone = applicant_phone;
record.applicant_address1 = applicant_address1;
record.applicant_address2 = applicant_address2;
record.applicant_city = applicant_city;
record.applicant_state = applicant_state;
record.applicant_zip = applicant_zip;
record.applicant_email = applicant_email;
return record;
}
public List<ApplicantRecord> GetList()
{
return Approval_Form.ApplicantRecord.ApplicantDL.GetList();
}
public void Insert()
{
applicant_ID = Approval_Form.ApplicantRecord.ApplicantDL.Insert(applicant_fname, applicant_lname, applicant_phone, applicant_address1, applicant_address2, applicant_city, applicant_state, applicant_zip, applicant_email);
}
public void Select(int applicant_ID)
{
ApplicantRecord record = Approval_Form.ApplicantRecord.ApplicantDL.Select(applicant_ID);
Rec2Members(record);
}
public void Update()
{
if (applicant_ID != 0)
{
Approval_Form.ApplicantRecord.ApplicantDL.Update(applicant_ID, applicant_fname, applicant_lname, applicant_phone, applicant_address1, applicant_address2, applicant_city, applicant_state, applicant_zip, applicant_email);
}
}
}
I think it should be:
private void BuildComboList()
{
Applicant defaultApplicant = new Applicant();
applicationList = defaultApplicant.GetList();
applicantList.DataSource = applicationList;
applicantList.DisplayMember = "Applicant_fname";
applicantList.ValueMember = "Applicant_ID";
}
You can change the applicant class further as follows:
Add two properties.
public string DisplayName
{
get { return (applicant_fname + " " + applicant_lname; }
}
public string DisplayValue
{
get { return (applicant_ID.ToString(); }
}
Keep data binding as:
private void BuildComboList()
{
Applicant defaultApplicant = new Applicant();
applicationList = defaultApplicant.GetList();
applicantList.DataSource = applicationList;
applicantList.DisplayMember = "DisplayName";
applicantList.ValueMember = "DisplayValue";
}