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;
}
}
}
Related
I want to set second label in info window on xamarin map. I use this example.
So exactly I want to set one variable who come from date base on info window like a second label:
public MapPage()
{
InitializeComponent();
DatabaseConnection();
CustomPin pin1 = new CustomPin
{
Type = PinType.Place,
Position = new Position(41.59043006333251, 24.766286971618303),
Name = "Xamarin",
Label = "р. Бяла",
Address = "гр. Смолян",
};
CustomPin pin2 = new CustomPin
{
Type = PinType.Place,
Position = new Position(41.56817473054596, 24.758451447799708),
Label = "р. Черна",
Name = "Xamarin",
Address = "гр. Смолян",
};
CustomPin pin3 = new CustomPin
{
Type = PinType.Place,
Position = new Position(41.48398466282902, 24.847715935872973),
Label = "р. Елховска",
Name = "Xamarin",
Address = "гр. Рудозем",
};
customMap.CustomPins = new List<CustomPin> {
pin1,
pin2,
pin3,
};
customMap.Pins.Add(pin1);
customMap.Pins.Add(pin2);
customMap.Pins.Add(pin3);
customMap.MoveToRegion(MapSpan.FromCenterAndRadius(new Position(41.567797926753485, 25.389703182725665), Distance.FromKilometers(70)));
}
try
{
Conn.Open();
string query = "SELECT * FROM sel_alert_level s;";
MySqlCommand myCommand = new MySqlCommand(query, Conn);
MySqlDataReader myReader;
myReader = myCommand.ExecuteReader();
try
{
while (myReader.Read())
{
var codeNum = myReader.GetInt32(4);
var level = myReader.GetInt32(3);
await DisplayAlert("Database Connection", "Connected .." + Environment.NewLine + myReader.GetInt32(0) + Environment.NewLine + myReader.GetString(1) + Environment.NewLine + myReader.GetString(2) + Environment.NewLine + myReader.GetInt32(3) + Environment.NewLine + myReader.GetInt32(4), "OK");
}
}
finally
{
myReader.Close();
Conn.Close();
}
}
I want var codeNum = myReader.GetInt32(4); to be on the pin info window.
In my android project in directory resource/layout I have two axml files for the info window:
XamarinMapInfoWindow.axml
and
MapInfoWindow.axml
Inside in both files I create a new TextView for the second label:
<TextView
android:id="#id/InfoWindowSubtitle2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="InfoWindowSubtitle2"
android:textColor="#android:color/black" />
On my CustomMapRenderer.cs file in android project I have method GetInfoContents in which I do not know how to submit the new label.
public Android.Views.View GetInfoContents(Marker marker)
{
var inflater = Android.App.Application.Context.GetSystemService(Context.LayoutInflaterService) as Android.Views.LayoutInflater;
if (inflater != null)
{
Android.Views.View view;
var customPin = GetCustomPin(marker);
if (customPin == null)
{
throw new Exception("Custom pin not found");
}
if (customPin.Name.Equals("Xamarin"))
{
view = inflater.Inflate(Resource.Layout.XamarinMapInfoWindow, null);
}
else
{
view = inflater.Inflate(Resource.Layout.MapInfoWindow, null);
}
var infoTitle = view.FindViewById<TextView>(Resource.Id.InfoWindowTitle);
var infoSubtitle = view.FindViewById<TextView>(Resource.Id.InfoWindowSubtitle);
var infoSubtitle2 = view.FindViewById<TextView>(Resource.Id.InfoWindowSubtitle2);
if (infoTitle != null)
{
infoTitle.Text = marker.Title;
}
if (infoSubtitle != null)
{
infoSubtitle.Text = marker.Snippet;
}
if (infoSubtitle2 != null)
{
infoSubtitle2.Text = marker.Snippet;
}
return view;
}
return null;
}
So
` if (infoSubtitle2 != null)
{
infoSubtitle2.Text = marker.Snippet;
}`
is not the correct code. Before this method in the same page I have CreateMarker method who add a new lines on the marker and here I also don't understand how to submit the new line:
protected override MarkerOptions CreateMarker(Pin pin)
{
var marker = new MarkerOptions();
marker.SetPosition(new LatLng(pin.Position.Latitude, pin.Position.Longitude));
marker.SetTitle(pin.Label);
marker.SetSnippet(pin.Address);
marker.SetIcon(BitmapDescriptorFactory.FromResource(Resource.Drawable.green));
return marker;
}
Finally I create a new object in the Pin class for Alert Level who will come from data base.
namespace CustomRenderer
{
public class CustomPin : Pin
{
public string Name { get; set; }
public string Url { get; set; }
public int CodeNum { get; set; }
public int AlertLevel { get; set; }
}
}
My main question is how to put var level = myReader.GetInt32(3); like a second Label on InfoWindow ?
You could get the CustomPin with the GetCustomPin method in the custom renderer like the sample in your above link.
CustomPin GetCustomPin(Marker annotation)
{
var position = new Position(annotation.Position.Latitude, annotation.Position.Longitude);
foreach (var pin in customPins)
{
if (pin.Position == position)
{
return pin;
}
}
return null;
}
and in your public Android.Views.View GetInfoContents(Marker marker) method:
public Android.Views.View GetInfoContents(Marker marker)
{
var inflater = Android.App.Application.Context.GetSystemService(Context.LayoutInflaterService) as Android.Views.LayoutInflater;
if (inflater != null)
{
Android.Views.View view;
var customPin = GetCustomPin(marker);
if (customPin == null)
{
throw new Exception("Custom pin not found");
}
if (customPin.Name.Equals("Xamarin"))
{
view = inflater.Inflate(Resource.Layout.XamarinMapInfoWindow, null);
}
else
{
view = inflater.Inflate(Resource.Layout.MapInfoWindow, null);
}
CustomPin pin = GetCustomPin(marker);
int CodeNum = pin.CodeNum; //get the pin,then get the codenum and alertlevel
string AlertLevel = pin.AlertLevel;
var infoTitle = view.FindViewById<TextView>(Resource.Id.InfoWindowTitle);
var infoSubtitle = view.FindViewById<TextView>(Resource.Id.InfoWindowSubtitle);
var infoSubtitle2 = view.FindViewById<TextView>(Resource.Id.InfoWindowSubtitle2);
var infoSubtitle3 = view.FindViewById<TextView>(Resource.Id.InfoWindowSubtitle3);// create the third TextView in your xml
if (infoTitle != null)
{
infoTitle.Text = marker.Title;
}
if (infoSubtitle != null)
{
infoSubtitle.Text = marker.Snippet;
}
if (infoSubtitle2 != null)
{
infoSubtitle2.Text = CodeNum +"";
}
if (infoSubtitle3 != null)
{
infoSubtitle3.Text = AlertLevel;
}
return view;
}
return null;
}
Update :
public partial class YouPage: ContentPage
{
public YouPage()
{
InitializeComponent();
}
protected async override void OnAppearing()
{
base.OnAppearing();
... //you get the data from MySql,if you have several data,you need a loop
var codeNum = xxx;
var level = xxx;
CustomPin pin = new CustomPin();
pin.CodeNum = codeNum;
pin.AlertLevel = level ;
yourcustomMap.Pins.Add(pin);
}
So I have a DataGrid which is bound to a ICollectionView.
Now, I have one column which I want it to be bound not to the ICollectionView, but to a local variable from inside of the class.
How do I make that in the code?
<DataGrid
x:Name="DG_StudentsList"
FontSize="20"
HorizontalContentAlignment="Center"
VerticalContentAlignment="Center"
AutoGenerateColumns="False">
<DataGrid.Columns>
<DataGridTextColumn Binding="{Binding Id}" Header="מ''ס"/>
<DataGridTextColumn Binding="{Binding Name}" Header="שם"/>
<DataGridTextColumn Binding="{Binding PhoneNum}" Header="טלפון"/>
<DataGridTemplateColumn Header="ספרים מושאלים">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<ComboBox ItemsSource="{Binding Path=BorrowedBooks}" DisplayMemberPath="BookName" SelectionChanged="CB_BookName_SelectionChanged"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
Just to be clear, I want to add a new DataGridTextColumn which is the one that will be bound to the local variable.
public partial class StudentsList : Window
{
ObservableCollection<Student> OBStudents = new ObservableCollection<Student>();
CollectionViewSource StudentsCollection;
Predicate<object> yourCostumFilter;
ICollectionView Itemlist;
Student s = Student.Instance;
//string ss = "wel welwel";
public StudentsList()
{
InitializeComponent();
InitializeObservableCollection();
}
private void InitializeObservableCollection()
{
foreach (var item in s.GetStudentList())
OBStudents.Add(item);
StudentsCollection = new CollectionViewSource { Source = OBStudents };
Itemlist = StudentsCollection.View;
DG_StudentsList.ItemsSource = Itemlist;
}
private void BTN_Exit_Click(object sender, RoutedEventArgs e)
{
this.Close();
}
private void Window_SizeChanged(object sender, SizeChangedEventArgs e)
{
}
private void Window_MouseDown(object sender, MouseButtonEventArgs e)
{
if (e.ChangedButton == MouseButton.Left)
this.DragMove();
}
private void CB_Filter_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (!string.IsNullOrEmpty(sender.ToString()))
TB_SearchBox.IsEnabled = true;
else
TB_SearchBox.IsEnabled = false;
}
private void TB_SearchBox_TextChanged(object sender, TextChangedEventArgs e)
{
if (CB_Filter.SelectedIndex == 0)
yourCostumFilter = new Predicate<object>(item => ((Student)item).Name.Contains(TB_SearchBox.Text));
else if (CB_Filter.SelectedIndex == 1)
yourCostumFilter = new Predicate<object>(item => ((Student)item).PhoneNum.Contains(TB_SearchBox.Text));
Itemlist.Filter = yourCostumFilter;
Itemlist.Refresh();
}
private void CB_BookName_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
ComboBox CB = (ComboBox)sender;
BookBorrowed borrowedBookDate,bbHolder =(BookBorrowed) CB.SelectedItem;
borrowedBookDate = s.GetBorrowedBookInfo((Student)DG_StudentsList.SelectedItem, bbHolder.BookName);
//ss = borrowedBookDate.BookLendDate.ToShortDateString();
/*DataGridTextColumn tc = new DataGridTextColumn();
tc.Header = "תאריך השאלה";
tc.Binding = new Binding("borrowedBookDate.BookLendDate, TargetNullValue=borrowedBookDate.BookLendDate");
DG_StudentsList.Columns.Add(tc);*/
}
}
public class Student
{
private readonly TextFileHandler TFH = TextFileHandler.Instance;
public List<string> Lines { get; private set; } = new List<string>();
private static readonly Lazy<Student> student = new Lazy<Student>(() => new Student());
public static Student Instance { get { return student.Value; } }
private Book b = Book.Instance;
private StudentsWindow SW;
public int Id { get; set; }
public string Name { get; set; }
public string PhoneNum { get; set; }
public List<BookBorrowed> BorrowedBooks { get; set; }
private Student() { }
private Student(int id, string name, string phoneNum, List<BookBorrowed> borrowedBooks)
{
Id = id;
Name = name;
PhoneNum = phoneNum;
BorrowedBooks = borrowedBooks;
}
public Student(string Name, string PhoneNum)
{
Id = GenerateID();
this.Name = Name;
this.PhoneNum = PhoneNum;
BorrowedBooks = new List<BookBorrowed>();
}
public Student(string Name, string PhoneNum, List<BookBorrowed> BorrowedBooks)
{
Id = GenerateID();
this.Name = Name;
this.PhoneNum = PhoneNum;
this.BorrowedBooks = BorrowedBooks;
}
public void AddStudent(Student newStudent)
{
SW = Application.Current.Windows.OfType<StudentsWindow>().First();
UpdateStudentsLinesList();
if (!TFH.CheckLineExistens($"שם:{newStudent.Name}", Paths.studentsFile) ||
!TFH.CheckLineExistens($"טלפון:{newStudent.PhoneNum}", Paths.studentsFile))
{
Lines.Add($"מ''ס:{GenerateID()}\n[");
Lines.Add($"שם:{newStudent.Name}");
Lines.Add($"טלפון:{newStudent.PhoneNum}");
Lines.Add($"ספרים מושאלים");
Lines.Add(#"{");
foreach (var book in newStudent.BorrowedBooks)
{
Lines.Add($"שם הספר:{book.BookName}");
Lines.Add($"תאריך השאלה:{DateTime.Now.ToShortDateString()}");
}
Lines.Add(#"}");
Lines.Add("]");
SW.WriteToConsole($"התלמיד {newStudent.Name} נוסף בהצלחה ");
}
else
{
SW.WriteToConsole($"התלמיד {newStudent.Name} כבר קיים במערכת ");
}
TFH.OverWriteFile(Lines, Paths.studentsFile);
}
public void AddStudentWithoutOuput(Student newStudent)
{
SW = Application.Current.Windows.OfType<StudentsWindow>().First();
UpdateStudentsLinesList();
if (!TFH.CheckLineExistens($"שם:{newStudent.Name}", Paths.studentsFile) ||
!TFH.CheckLineExistens($"טלפון:{newStudent.PhoneNum}", Paths.studentsFile))
{
Lines.Add($"מ''ס:{GenerateID()}\n[");
Lines.Add($"שם:{newStudent.Name}");
Lines.Add($"טלפון:{newStudent.PhoneNum}");
Lines.Add($"ספרים מושאלים");
Lines.Add(#"{");
foreach (var book in newStudent.BorrowedBooks)
{
Lines.Add($"שם הספר:{book.BookName}");
Lines.Add($"תאריך השאלה:{DateTime.Now.ToShortDateString()}");
}
Lines.Add(#"}");
Lines.Add("]");
}
TFH.OverWriteFile(Lines, Paths.studentsFile);
}
public void AddBookToStudent(Book newBook, Student student)
{
SW = Application.Current.Windows.OfType<StudentsWindow>().First();
bool bookExist = false;
student.BorrowedBooks.ForEach(bookName => {
if (bookName.Equals(newBook.BookName))
bookExist = true;
});
if (
!bookExist &
newBook.Quantity != 0)
{
student.BorrowedBooks.Add(new BookBorrowed(newBook.BookName));
StudentWithUpdatedBooks(student);
Book bookWithLowerQuantity = new Book(newBook);
bookWithLowerQuantity.Quantity--;
b.UpdateInfo(newBook, bookWithLowerQuantity);
SW.WriteToConsole($"הספר {newBook.BookName} נוסף בהצלחה לתלמיד {student.Name}");
SW.WriteToConsole($"כמות הספרים הנותרים מהספר {newBook.BookName}: {bookWithLowerQuantity.Quantity}");
}
else
{
if(bookExist)
SW.WriteToConsole($"הספר {newBook.BookName} כבר קיים אצל התלמיד {student.Name}");
else if(newBook.Quantity == 0)
SW.WriteToConsole($"אין עוד מספר זה בסיפרייה. כמות הספרים מהספר {newBook.BookName}: {newBook.Quantity--}");
}
}
public void DeleteStudent(Student student)
{
UpdateStudentsLinesList();
if (TFH.CheckLineExistens($"שם:{student.Name}", Paths.studentsFile) &
TFH.CheckLineExistens($"טלפון:{student.PhoneNum}", Paths.studentsFile))
{
if (student.BorrowedBooks.Count != 0)
{
List<Book> booksStudentHave = new List<Book>(), booksToReturn = new List<Book>();
student.BorrowedBooks.ForEach(bookName => {
booksStudentHave.Add(b.GetBookByInfo($"שם:{bookName}"));
});
booksStudentHave.ForEach(book => {
Book bHolder = new Book(book);
bHolder.Quantity += book.Quantity;
b.UpdateInfo(book,bHolder);
});
}
bool inMidName = false, inMidPhone = false, insindMide = false;
List<string> newList = new List<string>();
int idLine = new int(), currentline = 1;
foreach (var line in Lines)
{
if (line.Equals($"שם:{student.Name}"))
inMidName = true;
if (line.Equals($"טלפון:{student.PhoneNum}"))
inMidPhone = true;
if (inMidName & inMidPhone)
{
idLine = currentline - 4;
break;
}
currentline++;
}
int id = int.Parse(Lines[idLine].Substring(Lines[idLine].IndexOf(":")+1));
foreach (var line in Lines)
{
if (line.Equals($"מ''ס:{id}"))
insindMide = true;
if (insindMide)
{
if (line.Equals("]"))
insindMide = false;
}
else
newList.Add(line);
}
TFH.OverWriteFile(newList, Paths.studentsFile);
}
}
public void DeleteStudent(string name, string phoneNum)
{
UpdateStudentsLinesList();
if (TFH.CheckLineExistens($"שם:{name}", Paths.studentsFile) &
TFH.CheckLineExistens($"טלפון:{phoneNum}", Paths.studentsFile))
{
bool inMidName = false, inMidPhone = false, insindMide = false;
List<string> newList = new List<string>();
int idLine = new int(), currentline = 1;
foreach (var line in Lines)
{
if (line.Equals($"שם:{name}"))
inMidName = true;
if (line.Equals($"טלפון:{phoneNum}"))
inMidPhone = true;
if (inMidName & inMidPhone)
{
idLine = currentline - 4;
break;
}
currentline++;
}
int id = int.Parse(Lines[idLine].Substring(Lines[idLine].IndexOf(":") + 1));
foreach (var line in Lines)
{
if (line.Equals($"מ''ס:{id}"))
insindMide = true;
if (insindMide)
{
if (line.Equals("]"))
insindMide = false;
}
else
newList.Add(line);
}
TFH.OverWriteFile(newList, Paths.studentsFile);
}
}
public void StudentWithUpdatedBooks(Student student)
{
bool inMid = false;
List<string> updatedList = new List<string>();
foreach (var line in TFH.GetAllRawLines(Paths.studentsFile))
{
if (line.Equals($"מ''ס:{student.Id}"))
inMid = true;
if (inMid)
{
if (line.Equals("]"))
inMid = false;
}
else
updatedList.Add(line);
}
TFH.OverWriteFile(updatedList, Paths.studentsFile);
AddStudentWithoutOuput(student);
}
public void UpdateInfo(Student student,Student updatedStudent)
{
bool inMid = false;
List<string> updatedList = new List<string>();
foreach (var line in TFH.GetAllRawLines(Paths.studentsFile))
{
if (line.Equals($"מ''ס:{student.Id}"))
inMid = true;
if (inMid)
{
if (line.Equals("]"))
inMid = false;
}
else
updatedList.Add(line);
}
TFH.OverWriteFile(updatedList,Paths.studentsFile);
AddStudentWithoutOuput(updatedStudent);
}
private int GenerateID()
{
int newID = 0;
foreach (string line in TFH.GetAllRawLines(Paths.studentsFile))
{
if (line.Contains("מ''ס:"))
newID++;
}
return newID;
}
public List<string> GetNewStudent(Student student)
{
UpdateStudentsLinesList();
List<string> newLines = new List<string>();
if (!TFH.CheckLineExistens($"שם:{student.Name}", Paths.studentsFile) &
!TFH.CheckLineExistens($"טלפון:{student.PhoneNum}", Paths.studentsFile))
{
Lines.Add($"מ''ס:{student.Id}\n[");
Lines.Add($"שם:{student.Name}");
Lines.Add($"טלפון:{student.PhoneNum}");
Lines.Add($"ספרים מושאלים");
Lines.Add(#"{");
foreach (var book in student.BorrowedBooks)
{
Lines.Add($"שם הספר:{book.BookName}");
Lines.Add($"תאריך השאלה:{DateTime.Now.ToShortDateString()}");
}
Lines.Add(#"}");
Lines.Add("]");
}
return newLines;
}
public List<Student> GetStudentList()
{
List<Student> newList = new List<Student>();
foreach (var line in TFH.GetAllRawLines(Paths.studentsFile))
{
if (line.Contains("מ''ס"))
newList.Add(GetStudentByInfo(line));
}
return newList;
}
public Student GetStudentByInfo(string info)
{
string name = null, phoneNum = null,BB_name = null;
int id = new int();
DateTime BB_lent;
List<BookBorrowed> borrowedBooks = new List<BookBorrowed>();
bool inMid = false, inMidBooks = false, insideBook = false;
if (info.Contains("מ''ס"))
{
foreach (var line in TFH.GetAllRawLines(Paths.studentsFile))
{
if (line.Equals(info))
{
inMid = true;
id = int.Parse(line.Substring(line.IndexOf(":") + 1));
}
if (inMid)
{
if (line.Equals("]"))
break;
else if (line.Contains("שם:"))
name = line.Substring(line.IndexOf(":") + 1);
else if (line.Contains("טלפון:"))
phoneNum = line.Substring(line.IndexOf(":") + 1);
else if (line.Equals("{"))
{
inMidBooks = true;
continue;
}
else if (line.Equals("}"))
inMidBooks = false;
if (inMidBooks)
{
if (line.Contains("שם הספר:"))
{
BB_name = line.Substring(line.IndexOf(":") + 1);
insideBook = true;
continue;
}
if (insideBook)
{
BB_lent = DateTime.Parse(line.Substring(line.IndexOf(":")+1));
borrowedBooks.Add(new BookBorrowed(BB_name,BB_lent));
insideBook = false;
}
}
}
}
return new Student(id, name, phoneNum, borrowedBooks);
}
return null;
}
public void UpdateStudentsLinesList() { Lines = TFH.GetAllRawLines(Paths.studentsFile); }
public BookBorrowed GetBorrowedBookInfo(Student student,string borrowedBookName)
{
Student currentStudent = GetStudentByInfo($"מ''ס:{student.Id}");
foreach (var book in currentStudent.BorrowedBooks)
{
if (book.BookName.Equals(borrowedBookName))
return new BookBorrowed(book.BookName, book.BookLendDate);
}
return null;
}
}
public class BookBorrowed
{
public string BookName { get; set; }
public DateTime BookLendDate { get; set; }
public BookBorrowed(string BookName)
{
this.BookName = BookName;
this.BookLendDate = DateTime.Now;
}
public BookBorrowed(string BookName, DateTime BookLendDate)
{
this.BookName = BookName;
this.BookLendDate = BookLendDate;
}
}
No, you can't bind to a local variable. First of all, there is a local scope, a instance scope and a class scope. A local variable only lives in a local scope e.g. the block of an if-statement or a method body. As soon the instruction pointer leaves this scope the variable does no longer exist. You may mean an instance variable i.e. field, which lives as long as the object instance is living. Class variables would be static fields, variables that don't belong to the class instance, but the class itself.
Anyway, you can only bind to public properties. Microsoft Docs: Binding Source Types
If you have a public property, then you can also bind a column to it.
A common CLR property would also work. But in controls it is recommended to implement properties that serve as a binding source as DependencyProperty.
Dependency properties overview, Data binding overview in WPF
MainWindow.xaml.cs
partial class MainWindow : Window
{
public static readonly DependencyProperty BorrowedBookDateProperty = DependencyProperty.Register(
"BorrowedBookDate",
typeof(DateTime),
typeof(MainWindow),
new PropertyMetadata(default(DateTime)));
public DateTime TextValue
{
get => (DateTime) GetValue(MainWindow.BorrowedBookDateProperty);
set => SetValue(MainWindow.BorrowedBookDateProperty, value);
}
public MainWindow()
{
this.BorrowedBook = DateTime.Now;
}
}
MainWindow.xaml
<Window>
<DataGrid>
<DataGrid.Columns>
<DataGridTextColumn Header="Borrowed Book Date"
Binding="{Binding RelativeSource={RelativeSource AncestorType=main:MainWindow}, Path=BorrowedBookDate}" />
</DataGrid.Columns>
</DataGrid>
</Window>
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();
}
}
}
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);
}
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