Xamarin forms ViewCell in listview - sending to the variable - c#

How can I send a data which is saved in a class:
public class Person
{
public int Id { get; set; }
public string Fullname { get; set; }
public string Details { get; set; }
public string UserType { get; set; }
}
to the variable?
I'm saving data (in another class) like this:
var persons = new List<Person>();
while (dr1.Read())
{
// get the results of each column
int id = (int)dr1["ID_Instructor"];
string firstname = (string)dr1["f_name"];
string lastname = (string)dr1["l_name"];
string school = (string)dr1["d_school"];
string category = (string)dr1["category"];
var person = new Person
{
Id = id,
Fullname = firstname + " " + lastname,
Details = school + " " + category
};
persons.Add(person);
}
and in the same class I want to send it to the variable from menuItem by the BindingContext. I just need to print all of this data (from one person from list)
private void MenuItem_Clicked_1(object sender, EventArgs e)
{
var menuItem = sender as MenuItem;
if (menuItem != null)
var name = menuItem.BindingContex;

Related

Adding an Array of Objects to another Class c#

I am attemping to read a text file in the format of
(The # at end is just the number of classes they're in, but I dont save the course name with the fac/students class)
Course Biology
Faculty Taylor Nate 0
Student Doe John 3
Student Sean Big 0
Course Art
Faculty Leasure Dan 1
The first input should be a course, followed by the faculty and students of the specific course. The Course class should contain a collection of faculty members and a collection of students.
I have been able to put each course/student/faculty into their respective class, but I am having trouble visualizing a way to add the students/faculty to the course.
My current idea putting the data into their respective classes would be to keep the current index of the course- therefore I have it saved as
courses[currentCourse++]
so when I parse the next line, (being a faculty/student) I already know what the course index should be.
using (StreamReader reader = new StreamReader(fileName))
{
while (!reader.EndOfStream)
{
lineCounter++;
line = reader.ReadLine();
string[] words = line.Split(' ');
Console.WriteLine(words[0]);
if (words[0] == "Course")
{
string nameOfCourse = words[1];
courses[currentCourse++] = new Course
{
Name = nameOfCourse
};
}
if (words[0] == "Faculty")
{
string firstName = words[1];
string lastName = words[2];
string numOfClasses = words[3];
faculty[currentFaculty++] = new Faculty
{
FirstName = firstName,
LastName = lastName,
NumOfClasses = numOfClasses,
};
}
if (words[0] == "Student")
{
string firstName = words[1];
string lastName = words[2];
string numOfClasses = words[3];
students[currentStudent++] = new Student
{
FirstName = firstName,
LastName = lastName,
NumOfClasses = numOfClasses,
};
}
I know the problem lies in the courses class itself- but i'm not sure the terminology to add a class to another class.
public class Course
{
public override string ToString()
{
return $"{Name}";
}
public string Name { get; set; }
}
public class Student
{
public override string ToString()
{
return $"{FirstName} {LastName} {NumOfClasses}";
}
public string FirstName { get; set; } = string.Empty;
public string LastName { get; set; } = string.Empty;
public string NumOfClasses { get; set; } = string.Empty;
}
Thanks for reading!
You want to add a collection of Student and Faculty to the course class, correct? You can do so like this by simply adding a List<T> to your Course class and then initializing it in a constructor.
public class Course
{
public override string ToString()
{
return $"{Name}";
}
public string Name { get; set; }
public List<Student> Students { get; set; }
public List<Faculty> FacultyMems { get; set; }
public Course()
{
Students = new List<Student>();
FacultyMems = new List<Faculty>();
}
}
And in your using block, you can add each student/faculty to the course as so:
if (words[0] == "Course")
{
string nameOfCourse = words[1];
currentCourse++;
courses[currentCourse] = new Course
{
Name = nameOfCourse
};
}
if (words[0] == "Faculty")
{
string firstName = words[1];
string lastName = words[2];
string numOfClasses = words[3];
courses[currentCourse].FacultyMems.Add(new Faculty
{
FirstName = firstName,
LastName = lastName,
NumOfClasses = numOfClasses,
});
}
if (words[0] == "Student")
{
string firstName = words[1];
string lastName = words[2];
string numOfClasses = words[3];
courses[currentCourse].Students.Add(new Student
{
FirstName = firstName,
LastName = lastName,
NumOfClasses = numOfClasses,
});
}
With this, each time you encounter "Course" your course list will add a new item and then you can append students/faculty/etc when those values occur.
This can be simplified even further but the concept is there for you to follow. Hope this helps.
If I'm understanding you correctly, you want your courses to have a list of faculty and students?
public class Course
{
public override string ToString()
{
return $"{Name}";
}
public string Name { get; set; }
public List<Student> Students { get; set; }
public List<Faculty> FacultyMembers {get; set;}
}
Just be sure to initialize the Lists before trying to add things to them otherwise you'll get a null ref exception.

Deserialize json data list in C#

public class information
{
public string name { get; set; }
public string surname { get; set; }
}
public class JsonFormat
{
public IList<information> information { get; set; }
}
protected void gettextbox_Click(object sender, EventArgs e)
{
JsonFormat newjson = new JsonFormat();
List<information> p = new List<information>();
information add1 = new information { name = textbox1.Text , surname = textbox2.Text };
information add2 = new information { name = textbox3.Text, surname = textbox4.Text };
p.Add(add1);
p.Add(add2);
newjson.information = p;
string json = JsonConvert.SerializeObject(newjson);
}
string json here :
"{\"information\":[{\"name\":\"data1\",\"surname\":\"data2\"}, \"name\":\"data3\",\"surname\":\"data4\"}]}"
it's okay here but, how can I deserialize the data on the list?
Thank you in advance for your help.
List<information> informationList = JsonConvert.DeserializeObject<List<information>>(json);
https://www.newtonsoft.com/json/help/html/DeserializeObject.htm

How to show only part of text in CheckedListBox

I'm creating an WindowsForms application that is using a list of persons with 4 parameters (ID, Name, Surname, Permissions):
public List<Osoba> ListaOsoba()
{
Osoba nr1 = new Osoba(1, "Name", "Surname", Permissions.Administrator);
Osoba nr2 = new Osoba(2, "Name2", "Surname2", Permissions.Użytkownik);
Osoba nr3 = new Osoba(3, "Name3", "Surname3", Permissions.Użytkownik);
listaOsób.Add(nr1);
listaOsób.Add(nr2);
listaOsób.Add(nr3);
return listaOsób;
}
I would like to post all those Parameters to CheckedListBox, but show only name and surname to the user. The ID and Permissions should be hidden, but they need to exist, because I want to use them later.
Every help will be appreciated.
public static bool CheckBoxListPopulate(CheckBoxList CbList, IList<T> liSource, string TextFiled, string ValueField)
{
try
{
CbList.Items.Clear();
if (liSource.Count > 0)
{
CbList.DataSource = liSource;
CbList.DataTextField = TextFiled;
CbList.DataValueField = ValueField;
CbList.DataBind();
return true;
}
else { return false; }
}
catch (Exception ex)
{ throw ex; }
finally
{
}
}
here Cb list is the control name and
List item Ilist is the list source name
Text field (should be concatination ) ="Name" + "Surname"
Value field will be Hidden it can be "1,2,3"
so only Text field will be visible to user
To bind only name and surname to checkedboxlist first store name and surname together and then try this:
NameS = "Name" + "Surname";
((ListBox)checkedListBox).DataSource = listaOsób;
((ListBox)checkedListBox).DisplayMember = "NameS";
try this, here you have to make arbitrary compound properties for display and value member like DisplayName and HiddenId and then you can easily bound with checkedlistbox.
public class Osoba
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public Permissions Permission { get; set; }
public string DisplayName { get; set; }
public string HiddenId { get; set; }
public Osoba()
{ }
public Osoba(int id, string fname, string lname, Permissions p)
{
Id = id;
FirstName = fname;
LastName = lname;
Permission = p;
DisplayName = FirstName + " " + LastName;
HiddenId = Id + "_" + Permission.GetHashCode();
}
public void ListaOsoba()
{
List<Osoba> objList = new List<Osoba>();
Osoba nr1 = new Osoba(1, "Name", "Surname", Permissions.Administrator);
Osoba nr2 = new Osoba(2, "Name2", "Surname2", Permissions.Uzytkownik);
Osoba nr3 = new Osoba(3, "Name3", "Surname3", Permissions.Uzytkownik);
objList.Add(nr1);
objList.Add(nr2);
objList.Add(nr3);
((ListBox)checkedListBox1).DataSource = objList;
((ListBox)checkedListBox1).DisplayMember = "DisplayName";
((ListBox)checkedListBox1).ValueMember = "HiddenId";
MessageBox.Show(((ListBox)checkedListBox1).Text);
MessageBox.Show(((ListBox)checkedListBox1).SelectedValue.ToString());
}
}
public enum Permissions
{
Administrator,
Uzytkownik
}
I had a similar thing with SQL. I returned many columns, but only wanted one to show.
Anyway
ArrayList arr = new ArrayList();
foreach (object o in ListaOsoba)
{
arr.Items.Add(o[1].ToString()+" "+o[2].ToString());
}
foreach (var item in arr)
{
chkNames.Items.Add(arr.ToString()); //chkNames is your CheckListBox
}
Then later when querying which ID and such goes where, loop through you original list, and see who was ticked based on the name and surname combo, find the ID related to that person and you should be sorted

How to make my object from combobox appear in listview

From the picture above you can see my program. The problem i have is that my combobox for Countries on the bottom does show up on my listview. I dont know why, has it to do with that Countries is not a string? and whats the solution. I have been trying for a very long time with this, i need all help there is for you guys to help. Thanks in advance
Form 1 = listview
Form 2 = my customer manager (the picture above)
down here is inside Form1
public partial class MainForm : Form
{
CustomerFiles.Contact contact = new CustomerFiles.Contact();
CustomerFiles.Address address = new CustomerFiles.Address();
CustomerFrame customerframe = new CustomerFrame();
private void MainForm_Load(object sender, EventArgs e)
{
if (customerframe.ShowDialog() == DialogResult.OK) //if button OK is clicked then value will be inserted
{
// var item = string.Format("[{0}]",contact.ToString());
listView1.Items.Add(string.Format("[{0}]", customerframe.ToString()));
}
}
Down here is inside Form2
public partial class CustomerFrame : Form
{
CustomerFiles.Address address = new CustomerFiles.Address();
CustomerFiles.Contact contact = new CustomerFiles.Contact();
CustomerFiles.Countries country = new CustomerFiles.Countries();
public string firstName { get; set; }
public string lastName { get; set; }
internal CustomerFiles.Phone phone { get; set; }
internal CustomerFiles.Email email { get; set; }
internal CustomerFiles.Address addressinfo { get; set; }
public string city { get; set; }
internal CustomerFiles.Countries countryinfo { get; set; }
public string street { get; set; }
public string zipcode { get; set; }
public CustomerFrame()
{
InitializeComponent();
List<CustomerFiles.Countries> countries = new List<CustomerFiles.Countries> {
new CustomerFiles.Countries{ CountryId = 1, Name = "Bulgaria"},
new CustomerFiles.Countries{ CountryId = 2, Name = "France"},
new CustomerFiles.Countries{ CountryId = 3, Name = "Brazil"},
new CustomerFiles.Countries{ CountryId = 4, Name = "Russia"},
new CustomerFiles.Countries{ CountryId = 5, Name = "South Africa"},
new CustomerFiles.Countries{ CountryId = 6, Name = "Kurdistan"},
new CustomerFiles.Countries{ CountryId = 7, Name = "China"},
new CustomerFiles.Countries{ CountryId = 8, Name = "Japan"},
new CustomerFiles.Countries{ CountryId = 9, Name = "United States of America"},
new CustomerFiles.Countries{ CountryId = 10, Name = "UK"},
new CustomerFiles.Countries{ CountryId = 11, Name = "Australia"},
new CustomerFiles.Countries{ CountryId = 12, Name = "Germany"},
new CustomerFiles.Countries{ CountryId = 13, Name = "Sweden"},};
cbCountry.DataSource = countries;
cbCountry.DisplayMember = "Name";
cbCountry.ValueMember = "CountryId";
cbCountry.SelectedValue = 1;
btnOk.DialogResult = DialogResult.OK;
contact.ToString();
address.ToString();
}
private void btnOk_Click(object sender, EventArgs e)
{
// inside contact
contact.FirstName = tbFirstName.Text;
firstName = contact.FirstName;
contact.LastName = tbLastName.Text;
lastName = contact.LastName;
contact.PhoneData = new CustomerFiles.Phone(tbCellPhone.Text);
phone = contact.PhoneData;
contact.PhoneData = new CustomerFiles.Phone(tbHomePhone.Text);
email = contact.EmailData;
//inside address class
address.City = tbCity.Text;
city = address.City;
address.Country = new CustomerFiles.Countries(cbCountry.Text);
countryinfo = address.Country;
address.Street = tbStreet.Text;
street = address.Street;
address.ZipCode = tbZipCode.Text;
zipcode = address.ZipCode;
}
public override string ToString()
{
return string.Format("[{0}, {1}]", contact.ToString(), address.ToString());
}
And down here is inside my address class
class Address
{
private string city;
public Countries country;
private string street;
private string strErrMessage;
private string zipCode;
public Address()
{
string strErrMessage = string.Empty;
string street = string.Empty;
string zipCode = string.Empty;
string city = string.Empty;
}
public Address(string street, string zipCode, string city)
{
Street = street;
ZipCode = zipCode;
City = city;
}
public Address(string street, string zipCode, string city, Countries country)
{
Street = street;
ZipCode = zipCode;
City = city;
Country = country;
strErrMessage = string.Empty;
}
public Countries Country
{
get
{
return country;
}
set
{
country = value;
}
}
public override string ToString()
{
return string.Format("[{0}, {1}, {2}, {3}]", city, zipCode, street, country);
}
}
It looks like you are adding the Text property from the form:
listView1.Items.Add(string.Format("[{0}]", customerframe.ToString()));
Change that to use the value you want to use. It's not very clear what you want to display in the ListView.
Maybe it's as simple as:
listView1.Items.Add(cbCountry.SelectedItem);
Check for null, etc.
Make sure your Country class overrides the ToString() function like you have in your other classes.

Can we create a dictionary with in a list in C#?

I have to create a list as follows :
name, roll no
subjectno, subject type
subject no, subject type
e.g.
name[0] = ron, roll no[0] = 12
subjectno[0]=1, subject type[0]="english"
subjectno[1]=12, subject type[1]="maths"
name[1] = elis, roll no[1] = 11
subjectno[0]=1, subject type[0]="english"
subjectno[1]=12, subject type[1]="maths"
subjectno[2]=14, subject type[2]="physics"
I am not sure how to do this in C#.
I tried making a list of student info and then for subject no and subject type i tried to make a dictionary.
I have written the code like this -
class Student
{
public class StudentInfo
{
public String name { get; set; }
public int rollno { get; set; }
Dictionary<String, String> subjects;
public StudentInfo(String name, int rollno)
{
this.name = name;
this.rollno = rollno;
}
public void addstudentinfo(string subjectno, string subjecttype)
{
if (subjects == null)
subjects = new Dictionary<string, string>();
subjects.Add(subjectno, subjecttype);
}
}
Here how I would do. First create these two class
public class Student
{
public int RollNo { get; set; }
public string Name { get; set; }
public Student(int rNo, string name)
{
this.RollNo = rNo;
this.Name = name;
}
public Student()
{
}
}
public class Subject
{
public int SubjectNo { get; set; }
public string Type { get; set; }
public Subject(int sNo, string sType)
{
this.SubjectNo = sNo;
this.Type = sType;
}
public Subject()
{
}
}
Then fill in the objects as follows :-
Dictionary<Student, List<Subject>> studentLists = new Dictionary<Student, List<Subject>>();
Student std = new Student() { RollNo = 11, Name = "John" };
List<Subject> sbj = new List<Subject>() {new Subject(020, "Math"),new Subject(030,"English") };
studentLists.Add(std, sbj);
Then iterate thru the Dictionary as follows:-
StringBuilder sb = new StringBuilder();
foreach (KeyValuePair<Student, List<Subject>> item in studentLists)
{
sb.Append("Student No : " + item.Key.RollNo + "<br />");
sb.Append("Student Name : " + item.Key.Name + "<br />");
foreach (var subjects in item.Value)
{
sb.Append("Subject No : " + subjects.SubjectNo + "<br />");
sb.Append("Subject Name : " + subjects.Type + "<br />");
}
}
Hope this helps.
Your requirements aren't clear, but it looks best to create a Subject class as well.
class Subject{
public int Id {get;set;}
public string Type {get;set;}
}
From there, you can change Dictionary<String, String> subjects to a simple List<Subject> type. And change addstudentinfo method to take a Subject as a parameter.
You can further improve it by ensuring that only one instance of a particular Subject ever exists by modifying the Subject class (For example, to use the Creator pattern).
You can create struct or class to contain student's info and than add it to Dictionary<string, StudInfo>, where string is student name as Key.
Class for storing student info:
public class StudInfo
{
public int RollNum;
public List<string> Activities = new List<string>();
public StudInfo(int num)
{
RollNum = num;
}
}
And its usage:
var dict = new Dictionary(string, StudInfo);
var info = new StudInfo(12);
dict.Add("Ellis", info);

Categories

Resources