WPF Datagrid Set Value Outside ICollectionView - c#

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>

Related

XML tests solve

I can't connect my XML file and my C# in microsoft visual studio. How do I solve this?
Here you find what need to be in your DA
public class LeegstaandXML
{
public string Index { get; set; }
public string Aard { get; set; }
public string Adres { get; set; }
public static int intElementsCount;
private List<LeegstaandXML> _leegstaand;
public List<LeegstaandXML> Lleegstaand
{
get
{
XmlDocument doc = new XmlDocument();
doc.Load("Lijst_leegstaande_bedrijfspanden.xml");
XmlNodeList elementlist = doc.GetElementsByTagName("fme:Lijst_leegstaande_bedrijfspanden");
intElementsCount = elementlist.Count;
_leegstaand = new List<LeegstaandXML>();
_leegstaand.Add(new LeegstaandXML()
{
Index = elementlist[Form1.counter]["fme:Dossier_ID"].InnerXml,
Adres = elementlist[Form1.counter]["fme:Adres"].InnerXml,
Aard = elementlist[Form1.counter]["fme:Aard_van_het_gebouw"].InnerXml,
});
return _leegstaand;
}
set
{
_leegstaand = value;
}
}
}
This is your connection in your form
private void btnVullen_Click(object sender, EventArgs e)
{
Leegstaand p = new Leegstaand();
do
{
counter++;
LeegstaandXML leegstaand2 = new LeegstaandXML();
foreach(LeegstaandXML lp in leegstaand2.Lleegstaand)
{
leegstaandDA NewItem = new leegstaandDA(lp.Index, lp.Adres, lp.Aard);
NewItem.AddItem();
//ListViewItem item = new ListViewItem(new string[] { lp.id.ToString(), lp.aard, lp.adres, lp.index.ToString() });
// item.Tag = lp;
//lsvLeegstaand.Items.Add(item);
}
} while (counter < LeegstaandXML.intElementsCount -1);
MessageBox.Show("implementatie is geslaagd");
counter = 0;
leegstaandDA.Getleegstaand();
foreach (Leegstaand l in leegstaandDA.Getleegstaand())
{
ListViewItem item = new ListViewItem(new string[] { l.index.ToString(), l.adres, l.aard});
item.Tag = l;
lsvLeegstaand.Items.Add(item);
}
}

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

Bind Long List Selector to result of POST method

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.

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