After deleting a row , it just do not vanishes from the screen - c#

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

Related

i want to update the quantity on a list box c# winform

how to update e specific value on a list..
for example when i click a button it adds the product on the list
name: coffe || quantity:1 || Price:2$
and when i click angain the same product the quantity increases by 1
i used this code but it doesnt change the number of the quantity.
private BindingList<recipt> Lista2 = new BindingList<recipt>();
private void addtolist(object sender, EventArgs e)
{
Button b = (Button)sender;
Product p = (Product)b.Tag;
recipt fat = new recipt ()
{
Name= p.Name,
quantity= 1,
price = p.Cmimi
};
bool found = false;
if (listBox1.Items.Count > 0)
{
foreach (var pr in Lista2)
{
if (pr.Name== p.Name)
{
pr.quantity= pr.quantity+ 1;
found = true;
}
}
if (!found)
{
fat.tot= fat.quantity* fat.price;
fat.Nr_bill = Convert.ToInt32(txtNrbill.Text);
Lista2.Add(fat);
}
}
else
{
fat.tot= fat.quantity* fat.price;
fat.Nr_bill = Convert.ToInt32(txtNrbill.Text);
Lista2.Add(fat);
}
fat.tot= fat.quantity* fat.price;
fat.Nr_bill = Convert.ToInt32(txtNrbill.Text);
Lista2.Add(fat);
pe.Faturs.Add(fat);
pe.SaveChanges();
Total = Total + (int)fat.price;
listBox1.SelectedIndex = listBox1.Items.Count - 1;
}
For updating values in ListBox automatically you need set BindingList of receipts to the ListBox.DataSource and make Receipt class implement INotifyPropertyChanged
public class Receipt : INotifyPropertyChanged
{
public string Name { get; }
public int Quantity { get; private set; }
public decimal Price { get; }
public string BillNumber { get; private set; }
public decimal Total => Price * Quantity;
public string Info => $"{nameof(Name)}: {Name} || {nameof(Quantity)}: {Quantity} || {nameof(Price)}: {Price:C} || {nameof(Total)}: {Total:C}";
public Receipt(string name, decimal price, string billNumber)
{
Name = name;
Price = price;
BillNumber = billNumber;
Quantity = 1;
}
public void AddOne()
{
Quantity += 1;
RaisePropertyChanged(nameof(Info));
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void RaisePropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
Then in the form
public class YourForm : Form
{
private readonly BindingList<Receipt> _Receipts;
public YourForm()
{
_Receipts = new BindingList<Receipt>();
listBox1.DisplayMember = "Info";
listBox1.DataSource = _Receipts;
}
private void AddToList(object sender, EventArgs e)
{
var button = (Button) sender;
var product = (Product) button.Tag;
var receiptInfo = _Receipts.FirstOrDefault(receipt => receipt.Name.Equals(product.Name));
if (receiptInfo == null)
{
receiptInfo = new Receipt(product.Name, product.Cmimi, txtNrbill.Text);
_Receipts.Add(receiptInfo);
}
else
{
receiptInfo.AddOne();
}
}
}

Dropdown has a SelectedValue which is invalid because it does not exist in the list of items, even though I cleared the selected items (C#)

I'm getting this error on DataBind(), and I don't know why since there shouldn't be anything selected.
DdState.Items.Clear();
DdState.DataSource = UsStates;
DdState.DataTextField = "Title";
DdState.DataValueField = "Title";
DdState.Items.Insert(0, String.Empty);
if (DdState.SelectedItem != null)
{
DdState.SelectedItem.Selected = false;
}
DdState.DataBind();
private IEnumerable<IStateItem> UsStates
{
get
{
var statesFolder = _sitecoreService.GetItem<ISitecoreItem>(ItemReference.BcsUs_ProductData_States.Guid);
if (statesFolder == null)
return new List<IStateItem>();
List<IStateItem> usStates = _sitecoreService.QueryChildren<IStateItem>(statesFolder).OrderBy(s => s.Title).ToList();
return usStates;
}
}
I tried putting in DdState.SelectedIndex = 0 before the DataBind(), but then I got an error that the selected index did not exist. What's going on?
If the DataSource is a list its much easier to implement. So just "convert" the UsStates IEnumerable to a List an then add it to the data source.
DdState.DataSource = UsStates.ToList();
Then choose the property of a list item as binding.
OR
public Form1()
{
InitializeComponent();
DdState.Items.Clear();
DdState.DataSource = UsStates;
DdState.DisplayMember = "Statename";
DdState.SelectedIndex = 0;
}
private List<IStateItem> UsStates
{
get
{
List<IStateItem> usStates = new List<IStateItem>();
usStates.Add(new IStateItem("California","status1"));
usStates.Add(new IStateItem("Ohio", "status3"));
return usStates;
}
}
private class IStateItem
{
public IStateItem(string statename, string stateStatus)
{
Statename = statename;
StateStatus = stateStatus;
}
public string Statename { get; set; }
public string StateStatus { get; set; }
}
Could there be something wrong with your IStateItem class?
I copy/pasted your code in a new asp.net application, made my own IStateItem class and it works.
using System;
using System.Collections.Generic;
namespace TestIt
{
public partial class Form1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
FillTheList();
}
private void FillTheList()
{
ddl_TheList.Items.Clear();
ddl_TheList.DataSource = UsStates;
ddl_TheList.DataTextField = "statename";
ddl_TheList.DataValueField = "stateStatus";
//ddl_TheList.Items.Insert(0, String.Empty);
ddl_TheList.DataBind();
ddl_TheList.SelectedIndex = 0;
}
private IEnumerable<IStateItem> UsStates
{
get
{
List<IStateItem> usStates = new List<IStateItem>();
for (int i = 0; i < 10; i++)
{
usStates.Add(new IStateItem { statename = "state #" + i, stateStatus = "cool state bro" });
}
return usStates;
}
}
}
public class IStateItem
{
public string statename { get; set; }
public string stateStatus { get; set; }
}
}

Update combobox MVVM (XAML & C#)

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).

Cannot delete selected a row from sqlite database

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);
}

Binding to New Member Display; BuildComboList

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";
}

Categories