Category Combobox and subcategory Binding Combobox - c#

I have a combobox category with 2 items ('usia' and 'serial') and when a user selects one item, for example: serial, it will display binding combobox containing serial subcategories.
XAML:
<ComboBox x:Name="kategoriBox" PlaceholderText="Kategori" FontSize="14" SelectionChanged="KategoriBox_SelectionChanged" Background="{x:Null}" BorderBrush="{x:Null}">
<ComboBoxItem>Usia</ComboBoxItem>
<ComboBoxItem>Serial</ComboBoxItem>
</ComboBox>
<ComboBox x:Name="usiaBox" PlaceholderText="Pilih Usia" ItemsSource="{x:Bind RatingList}" FontSize="14" SelectionChanged="UsiaBox_SelectionChanged" Background="{x:Null}" BorderBrush="{x:Null}"/>
<ComboBox x:Name="serialBox" Margin="15,0,0,0" PlaceholderText="Pilih Serial" ItemsSource="{x:Bind SerialList}" FontSize="14" SelectionChanged="SerialBox_SelectionChanged" Background="{x:Null}" BorderBrush="{x:Null}"/>
Code:
private void KategoriBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
string selectedcmb = ((ComboBoxItem)kategoriBox.SelectedItem).Content.ToString();
if (selectedcmb == "Usia")
{
UsiaC();
usiaBox.Visibility = Visibility.Visible;
serialBox.Visibility = Visibility.Collapsed;
}
else if (selectedcmb == "Serial")
{
SerialC();
usiaBoX.Visibility = Visibility.Collapsed;
serialBox.Visibility = Visibility.Visible;
}
}
private async void UsiaC()
{
try
{
string urlPath = "https://..../api-v3/Fetch/rating";
var httpClient = new HttpClient(new HttpClientHandler());
var values = new List<KeyValuePair<string, string>>
{
};
httpClient.DefaultRequestHeaders.TryAddWithoutValidation("SCH-API-KEY", "SCH_KEnaBiDeplebt");
var response = await httpClient.PostAsync(urlPath, new FormUrlEncodedContent(values));
response.EnsureSuccessStatusCode();
if (!response.IsSuccessStatusCode)
{
busyindicator.IsActive = false;
}
string jsonText = await response.Content.ReadAsStringAsync();
JsonObject jsonObject = JsonObject.Parse(jsonText);
JsonArray jsonData = jsonObject["data"].GetArray();
foreach (JsonValue groupValue in jsonData)
{
JsonObject groupObject1 = groupValue.GetObject();
string id = groupObject1["id"].GetString();
string name = groupObject1["rating"].GetString();
Rating rate = new Rating();
rate.ID = id;
rate.Name = name;
RatingList.Add(new Rating()
{
ID = rate.ID,
Name = rate.Name
});
}
}
catch(Exception)
{
busyindicator.IsActive = false;
umurID = "";
}
}
}
private async void SerialC()
{
try
{
string urlPath = "https://.../api-v3/Fetch/serial";
var httpClient = new HttpClient(new HttpClientHandler());
var values = new List<KeyValuePair<string, string>>
{
};
httpClient.DefaultRequestHeaders.TryAddWithoutValidation("SCH-API-KEY", "SCH_KEnaBiDeplebt");
var response = await httpClient.PostAsync(urlPath, new FormUrlEncodedContent(values));
response.EnsureSuccessStatusCode();
if (!response.IsSuccessStatusCode)
{
busyindicator.IsActive = false;
}
string jsonText = await response.Content.ReadAsStringAsync();
JsonObject jsonObject = JsonObject.Parse(jsonText);
JsonArray jsonData = jsonObject["data"].GetArray();
foreach (JsonValue groupValue in jsonData)
{
JsonObject groupObject1 = groupValue.GetObject();
string id = groupObject1["id"].GetString();
string name = groupObject1["nama"].GetString();
string slug = groupObject1["slug"].GetString();
Serial seri = new Serial();
seri.ID = id;
seri.Name = name;
seri.Slug = slug;
SerialList.Add(new Serial()
{
ID = seri.ID,
Name = seri.Name,
Slug = seri.Slug
});
}
}
catch(Exception)
{
busyindicator.IsActive = false;
serialID = "";
}
}
}
private void UsiaBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (usiaBox.SelectedIndex != -1)
{
var comboBox = sender as ComboBox;
Usia value = comboBox.SelectedItem as Rating;
usiaID = value.ID;
serialID = "";
}
else
{
usiaID = "";
}
}
private void SerialBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if(serialBox.SelectedIndex != -1)
{
var comboBox = sender as ComboBox;
Serial value = comboBox.SelectedItem as Serial;
serialID = value.ID;
usiaID = "";
}
else
{
serialID = "";
}
}
Usia.cs
class Usia
{
public string ID { get; set; }
public string Name { get; set; }
public override string ToString()
{
return this.Name;
}
}
Serial.cs
class Serial
{
public string ID { get; set; }
public string Name { get; set; }
public string Slug { get; set; }
public override string ToString()
{
return this.Name;
}
}
I have a problem, namely: I chose 'serial' on the category combobox then chose the subcategory. Then I chose 'usia' on the combobox category then chose the subcategory. Then I re-select 'serial' on the category and click the subcategory, then an error message will appear as shown below:
How to handle it?

Related

WPF Datagrid Set Value Outside ICollectionView

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>

Display Multiple JsonObject on Listview

I have a Json from the server as below:
{
"data": {
"komik_popular": {
"title": "Yei! Komik Awas Nyamuk Jahat jadi literasi terpopuler minggu ini lho!"
},
"buku_baru": {
"title": "Ada buku baru nih, Katalog Prasekolah"
}
},
}
I want to display the json on the listview, but I try Debug.Writeline("judul: " + highlight.Title) first
Code:
Highlight highlight = new Highlight();
string title = "";
string urlPath = link;
var httpClient = new HttpClient(new HttpClientHandler());
var values = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>("SCH-API-KEY", "SCH_KEnaBiDeplebt")
};
var response = await httpClient.PostAsync(urlPath, new FormUrlEncodedContent(values));
response.EnsureSuccessStatusCode();
string jsonText = await response.Content.ReadAsStringAsync();
try
{
JsonObject jsonObject = JsonObject.Parse(jsonText);
JsonObject jsonData = jsonObject["data"].GetObject();
JsonObject bukuBObject = jsonData.ContainsKey("buku_baru") && jsonData["buku_baru"] != null ? jsonData["buku_baru"].GetObject() : JsonObject.Parse("");
try
{
title = bukuBObject["title"].GetString();
}
catch
{
}
JsonObject komikPObject = jsonData.ContainsKey("komik_popular") && jsonData["komik_popular"] != null ? jsonData["komik_popular"].GetObject() : JsonObject.Parse("");
try
{
title = komikPObject["title"].GetString();
}
catch
{
}
highlight.Title = title;
Debug.WriteLine("judul: " + highlight.Title);
}
Highlight.cs:
class Highlight
{
public string Title { get; set; }
}
I'm having a problem, when I try to debug only the title on "komik_popular" is displayed, I want all the data in "komik_popular" and "buku_baru" to be displayed. How to handle it?
private List<Highlight > HighlightList = new List<Highlight>();
string urlPath = link;
var httpClient = new HttpClient(new HttpClientHandler());
var values = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>("SCH-API-KEY", "SCH_KEnaBiDeplebt")
};
var response = await httpClient.PostAsync(urlPath, new FormUrlEncodedContent(values));
response.EnsureSuccessStatusCode();
string jsonText = await response.Content.ReadAsStringAsync();
try
{
JsonObject jsonObject = JsonObject.Parse(jsonText);
JsonObject jsonData = jsonObject["data"].GetObject();
JsonObject komikPObject = jsonData.ContainsKey("komik_popular") && jsonData["komik_popular"] != null ? jsonData["komik_popular"].GetObject() : JsonObject.Parse("");
try
{
Highlight highlight = new Highlight();
string title = "";
title = komikPObject["title"].GetString();
HighlightList.Add(highlight);
}
catch
{
}
JsonObject bukuBObject = jsonData.ContainsKey("buku_baru") && jsonData["buku_baru"] != null ? jsonData["buku_baru"].GetObject() : JsonObject.Parse("");
try
{
Highlight highlight = new Highlight();
string title = "";
title = bukuBObject["title"].GetString();
HighlightList.Add(highlight);
}
catch
{
}
}
catch
{
}
foreach( Highlight items in HighlightList)
{
Debug.WriteLine("judul: " + items .Title);
}
}
for converting json data to list, first you have to create respective class model as per given data format after that you can convert or deserialize it in your list format , in cae of your json data you can follow below example :-
public class Titel
{
public string title { get; set; }
}
public class Data
{
public Titel komik_popular { get; set; }
public Titel buku_baru { get; set; }
}
public class RootObject
{
public Data data { get; set; }
}
class Program
{
static void Main(string[] args)
{
string s = "{'data':{'komik_popular':{'title':'Yei! Komik Awas Nyamuk Jahat jadi literasi terpopuler minggu ini lho!'},'buku_baru':{'title':'Ada buku baru nih, Katalog Prasekolah'}}}";
List<RootObject> dataList = JsonConvert.DeserializeObject<List<RootObject>>(s);
}
}

Several combobox categories with several combobox subcategories

I have 2 comboboxes with 2 categories and 2 types of subcategories. Combobox categories contain "Usia" and "Serial". Whereas the subcategory combobox retrieves data from the json server. If you select "Usia" in the combobox category, it will display "ratingBox" in the combobox subcategory, and if you select "Serial" in the combobox category, it will display "serialBox" in the combobox subcategory.
XAML:
<StackPanel x:Name="comboBoxStack" Grid.Row="0" Margin="30,15,0,0" Orientation="Horizontal">
<ComboBox x:Name="kategoriBox" PlaceholderText="Kategori" FontSize="14" SelectionChanged="KategoriBox_SelectionChanged">
<ComboBoxItem>Usia</ComboBoxItem>
<ComboBoxItem>Serial</ComboBoxItem>
</ComboBox>
<ComboBox x:Name="ratingBox" Margin="15,0,0,0" PlaceholderText="Pilih Usia" ItemsSource="{x:Bind RatingList}" FontSize="14" SelectionChanged="RatingBox_SelectionChanged"/>
<ComboBox x:Name="serialBox" Margin="15,0,0,0" PlaceholderText="Pilih Serial" ItemsSource="{x:Bind SerialList}" FontSize="14" SelectionChanged="SerialBox_SelectionChanged"/>
</StackPanel>
Code:
List<Rating> RatingList = new List<Rating>();
List<Serial> SerialList = new List<Serial>();
string umurID = "";
string serialID = "";
private void KategoriBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
var comboBoxItem = kategoriBox.Items[kategoriBox.SelectedIndex] as ComboBoxItem;
if (comboBoxItem != null)
{
string selectedcmb = comboBoxItem.Content.ToString();
if(selectedcmb == "Usia")
{
ratingBox.Visibility = Visibility.Visible;
serialBox.Visibility = Visibility.Collapsed;
RatingC();
ratingBox.SelectedIndex = -1;
}
else if(selectedcmb == "Serial")
{
ratingBox.Visibility = Visibility.Collapsed;
serialBox.Visibility = Visibility.Visible;
SerialC();
serialBox.SelectedIndex = -1;
}
}
else
{
ratingBox.Visibility = Visibility.Visible;
serialBox.Visibility = Visibility.Collapsed;
RatingC();
}
}
private async void RatingC()
{
serialID = "";
ConnectionProfile connections = NetworkInformation.GetInternetConnectionProfile();
if (connections != null && connections.GetNetworkConnectivityLevel() == NetworkConnectivityLevel.InternetAccess)
{
try
{
string urlPath = "https://..../Fetch/rating";
var httpClient = new HttpClient(new HttpClientHandler());
var values = new List<KeyValuePair<string, string>>
{
};
httpClient.DefaultRequestHeaders.TryAddWithoutValidation("SCH-API-KEY", "SCH_KEnaBiDeplebt");
var response = await httpClient.PostAsync(urlPath, new FormUrlEncodedContent(values));
response.EnsureSuccessStatusCode();
if (!response.IsSuccessStatusCode)
{
busyindicator.IsActive = false;
}
string jsonText = await response.Content.ReadAsStringAsync();
JsonObject jsonObject = JsonObject.Parse(jsonText);
JsonArray jsonData = jsonObject["data"].GetArray();
foreach (JsonValue groupValue in jsonData)
{
JsonObject groupObject1 = groupValue.GetObject();
string id = groupObject1["id"].GetString();
string name = groupObject1["rating"].GetString();
Rating rate = new Rating();
rate.ID = id;
rate.Name = name;
RatingList.Add(new Rating()
{
ID = rate.ID,
Name = rate.Name
});
}
}
catch
{
busyindicator.IsActive = false;
}
}
}
private async void SerialC()
{
umurID = "";
ConnectionProfile connections = NetworkInformation.GetInternetConnectionProfile();
if (connections != null && connections.GetNetworkConnectivityLevel() == NetworkConnectivityLevel.InternetAccess)
{
try
{
string urlPath = "https://.../Fetch/serial";
var httpClient = new HttpClient(new HttpClientHandler());
var values = new List<KeyValuePair<string, string>>
{
};
httpClient.DefaultRequestHeaders.TryAddWithoutValidation("SCH-API-KEY", "SCH_KEnaBiDeplebt");
var response = await httpClient.PostAsync(urlPath, new FormUrlEncodedContent(values));
response.EnsureSuccessStatusCode();
if (!response.IsSuccessStatusCode)
{
busyindicator.IsActive = false;
}
string jsonText = await response.Content.ReadAsStringAsync();
JsonObject jsonObject = JsonObject.Parse(jsonText);
JsonArray jsonData = jsonObject["data"].GetArray();
foreach (JsonValue groupValue in jsonData)
{
JsonObject groupObject1 = groupValue.GetObject();
string id = groupObject1["id"].GetString();
string name = groupObject1["nama"].GetString();
string slug = groupObject1["slug"].GetString();
Serial seri = new Serial();
seri.ID = id;
seri.Name = name;
seri.Slug = slug;
SerialList.Add(new Serial()
{
ID = seri.ID,
Name = seri.Name,
Slug = seri.Slug
});
}
}
catch
{
busyindicator.IsActive = false;
}
}
}
private void RatingBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if(ratingBox.SelectedIndex != -1)
{
var comboBox = sender as ComboBox;
Rating value = comboBox.SelectedItem as Rating;
umurID = value.ID;
}
}
private void SerialBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if(serialBox.SelectedIndex != -1)
{
var comboBox = sender as ComboBox;
Serial value = comboBox.SelectedItem as Serial;
serialID = value.ID;
}
}
Rating.cs:
class Rating
{
public string ID { get; set; }
public string Name { get; set; }
public override string ToString()
{
return this.Name;
}
}
Serial.cs same as Rating.cs
I have a problem, that is if I have chosen "Usia" in the combobox category, then the combobox subcategory for that category can display data on the server smoothly, then I choose "Serial" in the combobox category, eating combobox subcategories for that category can display data on the server with smoothly. Then I again chose "Usia" in the combobox category, so when I click on the subcategory, an error message appears as shown below:
And here is my PC screen video for my problem:
https://1drv.ms/v/s!Auqiv8Ukng7UgP8Fj-LMDa9skV3yfA
In the video when re-selecting "Usia" in the combobox category (at the end of the video), it will display an error message as shown above
How to handle it?

RecyclerView check CheckBox and store in database

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

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.

Categories