C# Save and repopulate data from array - c#

I am working on a C# program that store the student name, student number, unit number, unit name, mark and attendance in an array. All the data are displayed in a ListView. How can I save the data from the array and then repopulate the array by using a Load Button? Thank you in advance.
public partial class Main : Form
{
public Main()
{
InitializeComponent();
//ListVIEW Properties
listView.View = View.Details;
listView.FullRowSelect = true;
}
private void insert(string StudentNumber, string StudentName, string UnitNumber, string UnitName, string Mark, string combobox)
{
// Array
string[] row = { StudentNumber, StudentName, UnitNumber, UnitName, Mark, combobox };
ListViewItem item = new ListViewItem(row);
listView.Items.Add(item);
}
private void update()
{
//Update
listView.SelectedItems[0].SubItems[0].Text = TXTStudentNumber.Text;
listView.SelectedItems[0].SubItems[1].Text = TXTStudentName.Text;
listView.SelectedItems[0].SubItems[2].Text = TXTUnitNumber.Text;
listView.SelectedItems[0].SubItems[3].Text = TXTUnitName.Text;
listView.SelectedItems[0].SubItems[4].Text = TXTMark.Text;
listView.SelectedItems[0].SubItems[5].Text = comboBox1.Text;
TXTStudentNumber.Text = "";
TXTStudentName.Text = "";
TXTUnitNumber.Text = "";
TXTUnitName.Text = "";
TXTMark.Text = "";
comboBox1.Text = "";
}
private void delete()
{
if (MessageBox.Show("Are you sure?", "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes)
{
listView.Items.RemoveAt(listView.SelectedIndices[0]);
}
TXTStudentNumber.Text = "";
TXTStudentName.Text = "";
TXTUnitNumber.Text = "";
TXTUnitName.Text = "";
TXTMark.Text = "";
comboBox1.Text = "";
}
private void btnInsert_Click(object sender, EventArgs e)
{
//Insert
insert(TXTStudentNumber.Text, TXTStudentName.Text, TXTUnitNumber.Text, TXTUnitName.Text, TXTMark.Text, comboBox1.Text);
// Clear All textBox after Pressing Button
TXTStudentNumber.Text = "";
TXTStudentName.Text = "";
TXTUnitNumber.Text = "";
TXTUnitName.Text = "";
TXTMark.Text = "";
comboBox1.Text = "";
}
//Update Button
private void btnUpdate_Click(object sender, EventArgs e)
{
update();
}
//Delete Button
private void btnDelete_Click(object sender, EventArgs e)
{
delete();
}
//Clear Button
private void btnClear_Click(object sender, EventArgs e)
{
TXTStudentNumber.Text = "";
TXTStudentName.Text = "";
TXTUnitNumber.Text = "";
TXTUnitName.Text = "";
TXTMark.Text = "";
comboBox1.Text = "";
}
// ListView
private void listView1_MouseClick(object sender, MouseEventArgs e)
{
TXTStudentNumber.Text = listView.SelectedItems[0].SubItems[0].Text;
TXTStudentName.Text = listView.SelectedItems[0].SubItems[1].Text;
TXTUnitNumber.Text = listView.SelectedItems[0].SubItems[2].Text;
TXTUnitName.Text = listView.SelectedItems[0].SubItems[3].Text;
TXTMark.Text = listView.SelectedItems[0].SubItems[4].Text;
comboBox1.Text = listView.SelectedItems[0].SubItems[5].Text;
}

array is not suitable in this case. Instead use list.
private List<Student> students = new List<Student>();
private void insert(string StudentNumber, string StudentName, string UnitNumber, string UnitName, string Mark, string combobox)
{
Student s = new Student
{
StudentNumber =StudentNumber,
StudentName =StudentName,
UnitNumber =UnitNumber
UnitName =UnitName,
Mark = Mark
Combobox = combobox
};
students.Add(s);
}
public class Student
{
public string StudentNumber{get; set;}
public string StudentName {get; set;}
public string UnitNumber {get; set;}
public string UnitName {get; set;}
public string Mark {get; set;}
public string Combobox {get;set;}
}

Follow the below steps
Add extension Method to convert your object to and from xml
ExtensionMethods class
public static class ExtensionMethods
{
/// <summary>
/// Converts given class to XML using xml serialization
/// </summary>
/// <typeparam name="T">Type of Class</typeparam>
/// <param name="classObject">Class to be serialized</param>
/// <returns>Xml string</returns>
public static string ToXML<T>(this T classObject) where T : class
{
XmlSerializer xmls = new XmlSerializer(typeof(T));
using (MemoryStream ms = new MemoryStream())
{
XmlWriterSettings settings = new XmlWriterSettings();
settings.Encoding = new UTF8Encoding(false);
settings.Indent = true;
settings.IndentChars = "\t";
settings.NewLineChars = Environment.NewLine;
settings.OmitXmlDeclaration = true;
settings.ConformanceLevel = ConformanceLevel.Document;
using (XmlWriter writer = XmlTextWriter.Create(ms, settings))
{
xmls.Serialize(writer, classObject);
}
string xml = Encoding.UTF8.GetString(ms.ToArray());
return xml;
}
}
/// <summary>
/// Converts given XML string to class of type T
/// </summary>
/// <typeparam name="T">Type to be converted</typeparam>
/// <param name="XmlData">xml string</param>
/// <returns>class of Type T</returns>
public static T ToClass<T>(this string XmlData)
{
XmlSerializer serializer = new XmlSerializer(typeof(T));
T newClass;
using (XmlTextReader reader = new XmlTextReader(new StringReader(XmlData)))
{
//reader.Namespaces = false;
newClass = (T)serializer.Deserialize(reader);
}
return newClass;
}
}
create a class to hold student information
student class
public class Student
{
public string StudentNumber{get; set;}
public string StudentName {get; set;}
public string UnitNumber {get; set;}
public string UnitName {get; set;}
public string Mark {get; set;}
public string Combobox {get;set;}
}
In form load check if file exists
Form load
//declare global variable for student list and filepath
List<Student> students = new List<Student>();
string FilePath = AppDomain.CurrentDomain.BaseDirectory + "\\" + Path.GetFileNameWithoutExtension(AppDomain.CurrentDomain.FriendlyName) + ".xml";
private void Form1_Load(object sender, EventArgs e)
{
string XmlData = string.Empty;
if (File.Exists(FilePath))
{
using (StreamReader sr = new StreamReader(FilePath))
{
XmlData = sr.ReadToEnd();
}
students = XmlData.ToClass<List<Student>>();
}
}
In insert,update and delete operations save the xml file to file system
save xml
string XmlData = students.ToXML();
File.WriteAllText(FilePath, XmlData);

Related

how to append to a c# list from form controls

I have a form with several text boxes. I want to use the input in the text boxes to append to a list in c# which I then want to show in a datagrid as the enteries are entered. But I have an issue. I add the data to the textboxes hit the display to datagrid button I have created and it seems ever time instead of appending items to the list the list is recreated. What am I doing wrong?
'''
{
public LotScan()
{
InitializeComponent();
}
public class LotData
{
public string Lot;
public string Description { get; set; }
public int PO { get; set; }
public string MfgPart { get; set; }
}
// code to add from control data to list
private List<LotData> LoadCollectionData()
{
List<LotData> lot = new List<LotData>();
lot.Add(new LotData()
{
Lot = LotNo.Text,
Description = frmDescription.Text,
PO = int.Parse(frmPO.Text),
MfgPart = frmMfgPart.Text,
});
return lot;
}
//button to add list data to datagrid on form
private void Button_Click(object sender, RoutedEventArgs e)
{
gridLotData.ItemsSource = LoadCollectionData();
LotNo.Text = String.Empty;
frmMfgPart.Text = string.Empty;
frmDescription.Text = String.Empty;
frmMfgPart.Text = string.Empty;
frmPO.Text = string.Empty;
}
'''
Move this variable to be a private Member variable (just put it a line above the classes constructor method):
List<LotData> lot = new List<LotData>();
public LotScan()
{
InitializeComponent();
gridLotData.ItemsSource = LotDataList;
}
private LotData LoadCollectionData()
{
return new LotData()
{
Lot = LotNo.Text,
Description = frmDescription.Text,
PO = int.Parse(frmPO.Text),
MfgPart = frmMfgPart.Text,
};
}
public class LotData
{
public string Lot;
public string Description { get; set; }
public int PO { get; set; }
public string MfgPart { get; set; }
}
public ObservableCollection<LotData> LotDataList = new ObservableCollection<LotData>();
private void Button_Click(object sender, RoutedEventArgs e)
{
LotDataList.Add(LoadCollectionData());
LotNo.Text = String.Empty;
frmMfgPart.Text = string.Empty;
frmDescription.Text = String.Empty;
frmMfgPart.Text = string.Empty;
frmPO.Text = string.Empty;
}

how to add instance to the list and then to the listbox in windows form

I don't know how to add Instances of my Album class from TextBoxes to a List<Album> and then to a ListBox in my WindowsForm.
Here is the code I have written so far but I'm stuck here and I don't know what to do next.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
List<Album> AlbumList = new List<Album>();
private void TrackButton_Click(object sender, EventArgs e)
{
addTracks settingsForm = new addTracks();
settingsForm.ShowDialog();
}
private void CreateButton_Click(object sender, EventArgs e)
{
Album g = new Album (ASINtextBox.Text, AlbumNametextBox.Text, ArtisttextBox.Text,
ReleaseDatePicker.Text, LabeltextBox.Text, ImagetextBox.Text);
AlbumList.Add(g);
}
}
I dont have eny error i just think it is not creating a new list when I'm debuging the program.
This is the code for the class:
eclass Album
{
private string ASIN;
private string AlbumName;
private string Artist;
private string ReleaseDate;
private string Label;
private string Image;
public Album(int ASIN)
{
this.ASIN = "no value";
this.AlbumName = "no value";
this.Artist = "no value";
this.ReleaseDate = "no value";
this.Label = "no value";
this.Image = "no value";
}
public Album(string ASIN, string AlbumName, string Artist, string ReleaseDate,
string Label, string Image)
{
this.ASIN = ASIN;
this.AlbumName = AlbumName;
this.Artist = Artist;
this.ReleaseDate = ReleaseDate;
this.Label = Label;
this.Image = Image;
}
public string aSIN
{
get { return this.ASIN; }
set { ASIN = value; }
}
public string albumName
{
get { return this.AlbumName; }
set { AlbumName = value; }
}
public string artist
{
get { return this.Artist; }
set { Artist = value; }
}
public string createDate
{
get { return this.ReleaseDate; }
set { ReleaseDate = value; }
}
public string label
{
get { return this.Label; }
set { Label = value; }
}
public string image
{
get { return this.Image; }
set { Image = value; }
}
}
Okay, you've got a few different options, but the easiest is something like this:
private void RefreshListBox()
{
myGuiListBox.Items.Clear();
foreach(Album loopAlbum in this.AlbumList)
{
myGuiListBox.Items.Add(loopAlbum.ToString());
}
}
... then, whenever something would change the list box (such as creating a new album and adding it to your List<>), you simply call the RefreshListBox() function.
I solved the listbox by not adding in the list box but just showing the values through the labels.
private void ShowAlbumsButton_Click(object sender, EventArgs e)
{
int temp = AlbumList.Count();
string talbumname = "";
string talbumasin = "";
string talbumartist = "";
string talbumrelease = "";
string talbumlabel = "";
for (int n =0; n<temp;n++)
{
talbumname = talbumname + AlbumList[n].albumName;
talbumname = talbumname + '\n';
talbumasin = talbumasin + AlbumList[n].aSIN;
talbumasin = talbumasin + '\n';
talbumartist = talbumartist + AlbumList[n].artist;
talbumartist = talbumartist + '\n';
talbumrelease = talbumrelease + AlbumList[n].createDate;
talbumrelease = talbumrelease + '\n';
talbumlabel = talbumlabel + AlbumList[n].label;
talbumlabel = talbumlabel + '\n';
}
label8.Text = talbumname;
label7.Text = talbumasin;
label9.Text = talbumartist;
label10.Text = talbumrelease;
label11.Text = talbumlabel;
}
thanks everyone for help.

String not getting value from string in requete.cs

I am not getting value from a string.
Exemple :
public static void ticket(string ticketName) // ticketName = "testTicket"
{
string abc = ticketName; // result : abc null
}
Can someone help me please I am stuck on it for almost 2 days
Here is real code
namespace FirstOutlookAddIn
{
public partial class lblSubject : Form
{
Outlook._Explorer currentExplorer = null;
private string Conversation_ID;
private string subject;
private string senderName;
private string senderEmail;
private string incident;
private DateTime creationDate;
public lblSubject()
{
InitializeComponent();
Outlook.Application myAPP = new Outlook.Application();
}
private void button3_Click(object sender, EventArgs e)
{
Outlook.Application myAPP = new Outlook.Application();
Outlook.MAPIFolder selectedFolder =
myAPP.Application.ActiveExplorer().CurrentFolder;
String expMessage = "Your current folder is "
+ selectedFolder.Name + ".\n";
String itemMessage = "Item is unknown.";
try
{
if (myAPP.Application.ActiveExplorer().Selection.Count > 0)
{
Object selObject = myAPP.Application.ActiveExplorer().Selection[1];
if (selObject is Outlook.MailItem)
{
Outlook.MailItem mailItem =
(selObject as Outlook.MailItem);
itemMessage = "The item is an e-mail message : Entery ID:"+ mailItem.EntryID+ " Conversation ID" + mailItem.ConversationID;
Conversation_ID = mailItem.ConversationID;
//mailItem.Display(false);
// Grab the Body
//txtBody.Text = mailItem.Body;
rIncident.Text = mailItem.Body;
incident = mailItem.Body;
senderName = mailItem.SenderName;
senderEmail = mailItem.SenderEmailAddress;
creationDate = mailItem.CreationTime;
Conversation_ID = mailItem.ConversationID;
// Sender Name
lblSenderName.Text = mailItem.SenderName;
// Sender Email
lblSenderEmail.Text = mailItem.SenderEmailAddress;
// Creation date
lblCreationdate.Text = mailItem.CreationTime.ToString();
}
}
private void lblSubject_Load(object sender, EventArgs e)
{
cboUsers.DataSource = Requetes.userliste();
cboPriority.DataSource = Requetes.priorityliste();
}
private void btnCreateTicket_Click(object sender, EventArgs e)
{
string userNom = cboUsers.SelectedItem.ToString();
string priorityNom = cboPriority.SelectedItem.ToString();
string convoID = Conversation_ID;
Requetes.saveTicket(userNom, priorityNom, subject,
senderName, senderEmail, incident, convoID, creationDate);
}
}
}
//Requete Class
namespace FirstOutlookAddIn
{
public static class Requetes
{
private static TicketingDBEntities6 ticketDB = new TicketingDBEntities6();
private static DateTime now = DateTime.Now;
//Recover User ID
public static void saveTicket(string userNom2, string priority, string subject,
string senderName, string email, string incident, string conversationID, DateTime mailCreateTime)
{
User u = ticketDB.User.Single(user1 => user1.User_Nom == userNom2);
int userIdenti = u.User_Id;
Priority p = ticketDB.Priority.Single(pr => pr.Priority_Name == priority);
int priorityID = p.Priority_Id;
Ticket t = new Ticket();
t.Ticket_Body = incident;
t.Ticket_ConversationID = conversationID;
t.Ticket_SenderEmail = email;
t.Ticket_SentDate = mailCreateTime;
t.Ticket_Priority = p.Priority_Id;
ObjectSet<Ticket> insert = ticketDB.Ticket;
insert.AddObject(t);
ticketDB.SaveChanges();
// Ticket ticket = ticketDB.Ticket.Single(ti => ti.Ticket_ConversationID == conversationID);
string getConvoID;
string getSenderEmail;
getSenderEmail = email;
DateTime dt = mailCreateTime;
getConvoID = conversationID;
var Users = (from uc in ticketDB.Ticket
where uc.Ticket_ConversationID == getConvoID
select uc
);
int abc = Users.Count();
Ticket_User tu = new Ticket_User();
tu.Ticket_User_Ticket_Id = ticket.Ticket_Id;
tu.Ticket_User_User_id = u.User_Id;
ObjectSet<Ticket_User> insert_Ticket_User = ticketDB.Ticket_User;
insert_Ticket_User.AddObject(tu);
ticketDB.SaveChanges();
}
}
}
THE PROBLEM IS WITH Classrequete
for exemple
if conversationID = "FFF1614651616fssd";t.Ticket_ConversationID = conversationID; // in debuget it shows conversationID is equal to "FF.....ssd" but t.Ticket_ConversationID is null:(((((((
`
Hope someone can help me out. Sorry for too much code code here
I guess you are trying to call ticket() method but you are not passing parameter to ticket("testTicket"), or when you try to call ticket(value) might be your variable is not getting value from source, I am very sure. everything is pretty straight forward.
Try to follow it:
public void SomeEvent()
{
string value = "testTicket";
ticket(value);
}
public static void ticket(string ticketName) // ticketName = "testTicket"
{
string abc = ticketName; // result : abc null
}
Good Luck.

Changing struct to class?

I want to change my struct Patient to a class but when I do my program don't work(free of errors) I want to substitute the struct patient for class patientn, as you can see my button click uses the struct patient and I want to change it for a class and still work.
visual studio 10 My program:
public partial class Form1 : Form
{
int itemCountInteger;
public struct Patient
{
public string patientidstring;
public string firstNameString;
public string lastNameString;
}
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
public class Patientn
{
private int patientId;
public string firstName;
private string lastName;
public Patientn()
{
patientId = 0;
firstName = "";
lastName = "";
}
public Patientn(int idValue, string firstNameVal, string lastNameVal)
{
patientId = idValue;
firstName = firstNameVal;
lastName = lastNameVal;
}
}
//Array
Patient[] patientInfo = new Patient[10];
//this method is used to add items to array and display listbox
private void button1_Click(object sender, EventArgs e)
{
try
{
foreach (Patient patientinfoIndex in patientInfo)
patientInfo[itemCountInteger].patientidstring = textBox1.Text;
patientInfo[itemCountInteger].firstNameString = textBox2.Text;
patientInfo[itemCountInteger].lastNameString = textBox3.Text;
string names = patientInfo[itemCountInteger].firstNameString + " " + patientInfo[itemCountInteger].lastNameString;
listBox1.Items.Add(names);
itemCountInteger++;
listBox1.SelectedItem = names;
}
catch
{
MessageBox.Show("Contacts are limited to 20. Please delete some contacts prior to adding more.");
}
}
You should explicitly create class instances. In your case
// It's quite enough since Patient is a struct
Patient[] patientInfo = new Patient[10];
In case of Patientn that is class it should be
// As it was...
Patientn[] patientInfo = new Patientn[10];
// You should add this since Patientn is a class
for (int i = 0; i < patientInfo.Length; ++i)
patientInfo[i] = new Patientn();

Silverlight 4.0 reading complex xml with linq

I'm stuck with following XML problem.
This is my XML file:
<POIs lastUsedId="9000010">
<POI id="9000010" name="München"><Latitude>48.139126</Latitude><Longitude>11.5801863</Longitude>
<Address>muenchen</Address><PhotoDescription>Hofbräuhaus</PhotoDescription>
<Photos directory="_x002F_pics"><PhotoFile>pic4poi_9000010-01.jpg</PhotoFile>
<PhotoFile>pic4poi_9000010-02.jpg</PhotoFile><PhotoFile>pic4poi_9000010-03.jpg</PhotoFile>
<PhotoFile>pic4poi_9000010-04.jpg</PhotoFile></Photos>
<InformationFile>infos\info4poi_9000010.txt</InformationFile></POI>
</POIs>
And here is my code to read the file:
XDocument doc = XDocument.Load(s);
lastID = Int32.Parse(doc.Root.Attribute("lastUsedId").Value.ToString());
CultureInfo cultureInfo = new CultureInfo("en-GB");
var pois = from res in doc.Descendants("POI")
select new
{
id = Int32.Parse(res.Attribute("id").Value.ToString()),
name = res.Attribute("name").Value.ToString(),
latitude = Double.Parse(res.Element("Latitude").Value, cultureInfo),
longitude = Double.Parse(res.Element("Longitude").Value, cultureInfo),
address = res.Element("Address").Value.ToString(),
photoDesc = res.Element("PhotoDescription").Value.ToString(),
photoDir = XmlConvert.DecodeName(res.Element("Photos").Attribute("directory").Value.ToString()),
photoFiles = from a in doc.Descendants("Photos")
select new
{
photo = a.Element("PhotoFile").Value.ToString()
},
info = res.Element("InformationFile").Value.ToString()
};
foreach (var poi in pois)
{
IEnumerable<string> pF = (poi.photoFiles as IEnumerable<string>);
List<string> photoFiles = null;
if(pF != null)
photoFiles = pF.ToList<string>();
AddPushpin(poi.id, poi.name, poi.latitude, poi.longitude, poi.address, poi.photoDesc, poi.photoDir, photoFiles, poi.info);
};
I'm unsure about the part with the PhotoFiles because I get an unknown Object error when I try to read the Pushpin.
This what my Pushpin looks like:
public class MyPushpin : Pushpin
{
public int ID { get; set; }
public string Address { get; set; }
public string PhotoDesc { get; set; }
public string PhotoDir { get; set; }
public List<string> PhotoFiles { get; set; }
public MyPushpin() { }
public MyPushpin(int id, string name, double latitude, double longitude, string address, string photoDesc, string photoDir, List<string> photoFiles, string info)
{
Location loc = new Location(latitude, longitude);
this.ID = id;
this.Location = loc;
this.Name = name;
this.Address = address;
this.PhotoDesc = photoDesc;
this.PhotoDir = photoDir;
this.PhotoFiles = photoFiles;
this.Tag = info;
}
public void Update(string name , string photoDesc, List<string> photoFiles, string info)
{
this.Name = name;
this.PhotoDesc = photoDesc;
this.PhotoFiles = photoFiles;
this.Tag = info;
}
public override string ToString()
{
return String.Format("{0} - {1}", this.ID, this.Location, this.Address, this.PhotoDesc, this.PhotoDir, this.Tag);
}
And that's the code how I would like to use the file info in the custom Pushpin:
public partial class Gallery : ChildWindow
{
List<string> pics = null;
public Gallery(MyPushpin currentPin)
{
InitializeComponent();
pics = currentPin.PhotoFiles;
Loaded += (a, b) => {
LoadImages();
};
}
private void OKButton_Click(object sender, RoutedEventArgs e)
{
this.DialogResult = true;
Close();
}
private void CancelButton_Click(object sender, RoutedEventArgs e)
{
this.DialogResult = false;
Close();
}
private void LoadImages()
{
List<Picture> coll = new List<Picture>();
pics.ForEach(delegate(String url)
{
coll.Add(AddPicture("url"));
});
//coll.Add(AddPicture("/pics/pic4poi_9000010-01.jpg"));
//coll.Add(AddPicture("/pics/pic4poi_9000010-02.jpg"));
//coll.Add(AddPicture("/pics/pic4poi_9000010-03.jpg"));
//coll.Add(AddPicture("/pics/pic4poi_9000010-04.jpg"));
Preview.Source = new BitmapImage(
new Uri(
"/pics/pic4poi_9000010-01.jpg",
UriKind.Relative));
lbImage.ItemsSource = coll;
}
private Picture AddPicture(string path)
{
return new Picture
{
Href = new BitmapImage(
new Uri(
path,
UriKind.Relative))
};
}
private void lbImage_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
Preview.Source = ((Picture)lbImage.SelectedItem).Href;
}
}
public class Picture
{
public ImageSource Href { get; set; }
THX for your time
Chau
Could you please describe the problem that you are having in more detail. Have you debugged into it, where does it fail, what is the exception? What do you expect it to do.
Off the top of my head, this code looks wrong:
photoFiles = from a in doc.Descendants("Photos")
select new
{
photo = a.Element("PhotoFile").Value.ToString()
},
Replace doc with res, because you want the child elements of the current element, not of the document. Also you can use Elements here instead of Descendants since they are direct children. Also since there are multiple photo files, try a SelectMany (from a ... from b ...):
photoFiles = from a in res.Elements("Photos")
from b in a.Elements("PhotoFile")
select new
{
photo = b.Value.ToString()
},

Categories