Child class can't acess data from parent class - c#

I've got the following code , where i define some operations to be done within a class and its variables:
namespace PPF_Converter_v10
{
public class ProgramStuff
{
protected List<String> OpenedFiles { get; private set; }
protected List<String> ValidFiles { get; private set; }
protected List<String> InvalidFiles { get; private set; }
protected List<String> FileData { get; private set; }
protected string FileContents { get; private set; }
public ProgramStuff()
{
OpenedFiles = new List<string>();
ValidFiles = new List<string>();
InvalidFiles = new List<string>();
FileData = new List<string>();
FileContents = string.Empty;
}
public void SelectFiles()
{
using (var FileSelect = new OpenFileDialog())
{
FileSelect.Multiselect = true;
FileSelect.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyComputer);
FileSelect.Filter = "PPF Files (*.ppf)|*.ppf|CIP Files (*.cip)|*.cip";
FileSelect.Title = "Seclect a PPF or CIP File";
DialogResult dr = FileSelect.ShowDialog();
if (dr == DialogResult.OK)
{
foreach(var File in FileSelect.FileNames)
{
OpenedFiles.Add(File);
}
}
}
}
public void ReadFiles()
{
foreach(var File in OpenedFiles)
{
using (var fs = new FileStream(File, FileMode.Open, FileAccess.ReadWrite, FileShare.None))
{
FileContents = string.Empty;
var len = (int)fs.Length;
var bits = new byte[len];
fs.Read(bits, 0, len);
// Dump 1024 bytes per line
for (int ix = 0; ix < len; ix += 1024)
{
//drawTextProgressBar(ix, (int)fs.Length);
var cnt = Math.Min(1024, len - ix);
var line = new byte[cnt];
Array.Copy(bits, ix, line, 0, cnt);
// Convert non-ascii characters to .
for (int jx = 0; jx < cnt; ++jx)
if (line[jx] < 0x20 || line[jx] > 0x7f) line[jx] = (byte)'.';
//Creating a big string with output
FileContents += Encoding.ASCII.GetString(line);
}
FileData.Add(FileContents);
}
}
}
public void FileDefiniton()
{
foreach(var File in FileData)
{
bool b = File.Contains("/HDMZoneCoverageValue") && File.Contains("/CIP3AdmInkColors");
if(b)
{
ValidFiles.Add(File);
}
else
{
InvalidFiles.Add(File);
}
}
}
public string XMLOutputFolder()
{
string XMLOutput = string.Empty;
using (var XMLOut = new FolderBrowserDialog())
{
XMLOut.ShowNewFolderButton = true;
XMLOut.RootFolder = Environment.SpecialFolder.MyComputer;
DialogResult dr = XMLOut.ShowDialog();
if(dr == DialogResult.OK)
{
XMLOutput = XMLOut.SelectedPath;
}
return XMLOutput;
}
}
public void ConvertedPPFFolder(string ConvertedPPF)
{
using (var ConvFolder = new FolderBrowserDialog())
{
ConvFolder.ShowNewFolderButton = true;
ConvFolder.RootFolder = Environment.SpecialFolder.MyComputer;
DialogResult dr = ConvFolder.ShowDialog();
if (dr == DialogResult.OK)
{
ConvertedPPF = ConvFolder.SelectedPath;
}
}
}
}//Closing class ProgramStuff
//Creating a child class called FileManipulation - manipulate files
public class FileManipulation: ProgramStuff
{
protected string PPFColors;
protected string[] ColorsNames;
public void ColorExtraction()
{
MessageBox.Show(ValidFiles.Count.ToString());
foreach (var data in ValidFiles)
{
Regex ColorNameRegex = new Regex("CIP3AdmSeparationNames(.*)CIP3AdmPSExtent");
var RegexAux = ColorNameRegex.Match(data);
PPFColors = RegexAux.Groups[1].ToString();
PPFColors = PPFColors.Replace("] def./", "").Replace("[", "").Replace(" (", "(").Replace("(", "").Replace(")", "|");
PPFColors = PPFColors.Remove(PPFColors.Length - 1, 1);
ColorsNames = PPFColors.Split(new[] { "|" }, StringSplitOptions.RemoveEmptyEntries);
}
}
}
}
Then, i have my form declaration, where i instantiate both and use them:
public partial class Form1 : Form
{
private FileManipulation FileOp;
private ProgramStuff GetFiles;
public Form1()
{
InitializeComponent();
FileOp = new FileManipulation();
GetFiles = new ProgramStuff();
}
private void button1_Click(object sender, EventArgs e)
{
GetFiles.SelectFiles();
GetFiles.ReadFiles();
GetFiles.FileDefiniton();
}
The question is: i can do all operations i need using the instantiated class ProgramStuff (called GetFiles). But, right here, when i call a method from the child class:
private void button5_Click(object sender, EventArgs e)
{
FileOp.ColorExtraction();
}
I can't acess data stored on the parent class. When debugging, the List called ValidFiles has 0 elements ; and there were elements added to it on the parent class. Is there way for me access those elements ? Thats the main point of my question.
Thanks !

I think the issue you have is that you are instantiating Child and Parent Class:
FileOp = new FileManipulation();
GetFiles = new ProgramStuff();
and you are trying to use data stored in two different objects.
As I see it, you only have to instantiate Child Class:
FileOp = new FileManipulation();
Then you will have to use FileOp on your code calling child and parents methods.
I hope it helps.

Related

Reordering DatagridViews Columns and Saving the new Position Programmatically

I have a datagridview in my Windows form.I need to allow the users to reorder the columns and then save the changes permanantly.I set
myGrid.AllowUserToOrderColumns = true;
But this only changes the display index on design only.
Maybe an old question but I figured out something I would consider simpler.
First, at the begining of your form class, add the following fields :
public partial class MyForm : Form
{
//So whenever you change the filename, you write it once,
//everyone will be updated
private const string ColumnOrderFileName = "ColumnOrder.bin";
//To prevent saving the data when we don't want to
private bool refreshing = false;
... // the rest of your class
Then, attach to the event ColumnDisplayIndexChanged with the following mehtod :
private void MyDataGridView_ColumnDisplayIndexChanged(object sender, DataGridViewColumnEventArgs e)
{
//Because when creating the DataGridView,
//this event will be raised many times and we don't want to save that
if (refreshing)
return;
//We make a dictionary to save each column order along with its name
Dictionary<string, int> order = new Dictionary<string, int>();
foreach (DataGridViewColumn c in dgvInterros.Columns)
{
order.Add(c.Name, c.DisplayIndex);
}
//Then we save this dictionary
//Note that you can do whatever you want with it...
using (FileStream fs = new FileStream(ColumnOrderFileName, FileMode.Create))
{
IFormatter formatter = new BinaryFormatter();
formatter.Serialize(fs, order);
}
}
Then comes the OrderColumns method :
private void OrderColumns()
{
//Will happen the first time you launch the application,
// or whenever the file is deleted.
if (!File.Exists(ColumnOrderFileName))
return;
using (FileStream fs = new FileStream(ColumnOrderFileName, FileMode.Open))
{
IFormatter formatter = new BinaryFormatter();
Dictionary<string, int> order = (Dictionary<string, int>)formatter.Deserialize(fs);
//Now that the file is open, we run through columns and reorder them
foreach (DataGridViewColumn c in MyDataGridView.Columns)
{
//If columns were added between two versions, we don't bother with it
if (order.ContainsKey(c.Name))
{
c.DisplayIndex = order[c.Name];
}
}
}
}
And finally, when you fill your DataGridView :
private void FillDataGridView()
{
refreshing = true; //To prevent data saving while generating the columns
... //Fill you DataGridView here
OrderColumns(); //Reorder the column from the file
refreshing = false; //Then enable data saving when user will change the order
}
Entity:
public class Customer : INotifyPropertyChanged
{
string _firstname = "";
public string Firstname
{
get { return _firstname; }
set { _firstname = value; OnPropertyChanged("Firstname"); }
}
string _lastname = "";
public string Lastname
{
get { return _lastname; }
set { _lastname = value; OnPropertyChanged("Lastname"); }
}
int _age = 0;
public int Age
{
get { return _age; }
set { _age = value; OnPropertyChanged("Age"); }
}
public Customer()
{
}
protected void OnPropertyChanged(string name)
{
var handler = PropertyChanged;
if (handler != null)
handler(this, new PropertyChangedEventArgs(name));
}
public event PropertyChangedEventHandler PropertyChanged;
}
The serializable Proxy:
[Serializable]
public class DataGridViewColumnProxy
{
string _name;
public string Name
{
get { return _name; }
set { _name = value; }
}
int _index;
public int Index
{
get { return _index; }
set { _index = value; }
}
public DataGridViewColumnProxy(DataGridViewColumn column)
{
this._name = column.DataPropertyName;
this._index = column.DisplayIndex;
}
public DataGridViewColumnProxy()
{
}
}
[Serializable]
public class DataGridViewColumnCollectionProxy
{
List<DataGridViewColumnProxy> _columns = new List<DataGridViewColumnProxy>();
public List<DataGridViewColumnProxy> Columns
{
get { return _columns; }
set { _columns = value; }
}
public DataGridViewColumnCollectionProxy(DataGridViewColumnCollection columnCollection)
{
foreach (var col in columnCollection)
{
if (col is DataGridViewColumn)
_columns.Add(new DataGridViewColumnProxy((DataGridViewColumn)col));
}
}
public DataGridViewColumnCollectionProxy()
{
}
public void SetColumnOrder(DataGridViewColumnCollection columnCollection)
{
foreach (var col in columnCollection)
if (col is DataGridViewColumn)
{
DataGridViewColumn column = (DataGridViewColumn)col;
DataGridViewColumnProxy proxy = this._columns.FirstOrDefault(p => p.Name == column.DataPropertyName);
if (proxy != null)
column.DisplayIndex = proxy.Index;
}
}
}
My Form1 for testing:
public partial class Form1 : Form
{
BindingSource _customers = GetCustomerList();
public BindingSource Customers
{
get { return _customers; }
set { _customers = value; }
}
public Form1()
{
InitializeComponent();
dataGridView1.DataSource = Customers;
LoadDataGridOrderFromFile("myDataGrid.xml", dataGridView1.Columns);
}
private static BindingSource GetCustomerList()
{
BindingSource customers = new BindingSource();
customers.Add(new Customer() { Firstname = "John", Lastname = "Doe", Age = 28 });
customers.Add(new Customer() { Firstname = "Joanne", Lastname = "Doe", Age = 25 });
return customers;
}
static object fileAccessLock = new object();
private static void SaveDataGridOrderToFile(string path, DataGridViewColumnCollection colCollection)
{
lock (fileAccessLock)
using (FileStream fs = new FileStream(path, FileMode.Create))
{
XmlSerializer xmlSerializer = new XmlSerializer(typeof(DataGridViewColumnCollectionProxy));
xmlSerializer.Serialize(fs, new DataGridViewColumnCollectionProxy(colCollection));
}
}
private static void LoadDataGridOrderFromFile(string path, DataGridViewColumnCollection colCollection)
{
if (File.Exists(path))
{
lock (fileAccessLock)
using (FileStream fs = new FileStream(path, FileMode.Open))
{
XmlSerializer xmlSerializer = new XmlSerializer(typeof(DataGridViewColumnCollectionProxy));
DataGridViewColumnCollectionProxy proxy = (DataGridViewColumnCollectionProxy)xmlSerializer.Deserialize(fs);
proxy.SetColumnOrder(colCollection);
}
}
}
private void dataGridView1_ColumnDisplayIndexChanged(object sender, DataGridViewColumnEventArgs e)
{
SaveDataGridOrderToFile("myDataGrid.xml", dataGridView1.Columns);
}
private void Form1_Load(object sender, EventArgs e)
{
dataGridView1.ColumnDisplayIndexChanged +=dataGridView1_ColumnDisplayIndexChanged;
}
}
It will save the DataPropertyName and the DisplayIndex into a xml file. You can extend / modify it easily where your data have to be stored by implementing your custom save and load methods.
This May Help you
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
m_Grid.AllowUserToOrderColumns = true;
SetDisplayOrder();
}
private void OnFormClosing(object sender, FormClosingEventArgs e)
{
CacheDisplayOrder();
}
private void CacheDisplayOrder()
{
IsolatedStorageFile isoFile =
IsolatedStorageFile.GetUserStoreForAssembly();
using (IsolatedStorageFileStream isoStream = new
IsolatedStorageFileStream("DisplayCache", FileMode.Create,
isoFile))
{
int[] displayIndices =new int[m_Grid.ColumnCount];
for (int i = 0; i < m_Grid.ColumnCount; i++)
{
displayIndices[i] = m_Grid.Columns[i].DisplayIndex;
}
XmlSerializer ser = new XmlSerializer(typeof(int[]));
ser.Serialize(isoStream,displayIndices);
}
}
private void SetDisplayOrder()
{
IsolatedStorageFile isoFile =
IsolatedStorageFile.GetUserStoreForAssembly();
string[] fileNames = isoFile.GetFileNames("*");
bool found = false;
foreach (string fileName in fileNames)
{
if (fileName == "DisplayCache")
found = true;
}
if (!found)
return;
using (IsolatedStorageFileStream isoStream = new
IsolatedStorageFileStream("DisplayCache", FileMode.Open,
isoFile))
{
try
{
XmlSerializer ser = new XmlSerializer(typeof(int[]));
int[] displayIndicies =
(int[])ser.Deserialize(isoStream);
for (int i = 0; i < displayIndicies.Length; i++)
{
m_Grid.Columns[i].DisplayIndex = displayIndicies[i];
}
}
catch { }
}
}
}

ObservableCollection binary serialization and transfer over the network

There is a small problem ka. there is a class
public class PLayer
{
public String Name{get;set;}
public TimeSpan Tax { get; set; }
}
The main form
public partial class MainWindow : Window
{
public ObservableCollection<PLayer> PlayersInGame { get; set; }
public ObservableCollection<PLayer> PlayersInGame2 { get; set; }
public ObservableCollection<PLayer> PlayersOnBench { get; set; }
public MainWindow()
{
PlayersInGame = new ObservableCollection<PLayer>();
PlayersInGame2 = new ObservableCollection<PLayer>();
PlayersOnBench = new ObservableCollection<PLayer>();
InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
for (int i = 0; i < 10; i++)
{
String vName = "Игрок" + i.ToString();
PlayersInGame.Add(new PLayer { Name = vName, Tax = new TimeSpan(0) });
}
for (int i = 10; i < 20; i++)
{
String vName = "Игрок" + i.ToString();
PlayersInGame2.Add(new PLayer { Name = vName, Tax = new TimeSpan(0) });
}
Game.Items.Refresh();
}
private void Button2_Click(object sender, RoutedEventArgs e)
{
if (Game.SelectedIndex > -1)
{
var temp = PlayersInGame[Game.SelectedIndex];
//PlayersInGame.RemoveAt(Game.SelectedIndex);
temp.Tax = new TimeSpan(0, 0, 5);
PlayersOnBench.Add(temp);
Game.Items.Refresh();
Bench.Items.Refresh();
}
if (Game2.SelectedIndex > -1)
{
var temp = PlayersInGame2[Game2.SelectedIndex];
//PlayersInGame2.RemoveAt(Game2.SelectedIndex);
temp.Tax = new TimeSpan(0, 0, 5);
PlayersOnBench.Add(temp);
Game2.Items.Refresh();
Bench.Items.Refresh();
}
}
private void timer_Tick(object sender, EventArgs e)
{
foreach (var x in PlayersOnBench)
{
x.Tax -= new TimeSpan(0, 0, 1);
}
List<int> Temp = new List<int>();
for (var i = 0; i < PlayersOnBench.Count; i++)
{
if (PlayersOnBench[i].Tax == TimeSpan.Zero)
{
Temp.Add(i);
}
}
for (int i = Temp.Count - 1; i >= 0; i--)
{
var s = PlayersOnBench[i];
PlayersOnBench.RemoveAt(Temp[i]);
//PlayersInGame.Add(s);
//Game.Items.Refresh();
}
Bench.Items.Refresh();
}
}
On the main form when you click on the button "Button2_Click" line is added to the ListView "Bench" with the addition of a timer. in the treatment of "timer_Tick" The timer is counting all the lines added to the "Bench". Contact ossushestvlyaetsya a Binding. My question is knowing binary serialization, how to transfer the contents of ListView "Bench" to the server to display in a ListView or ListBox. The binary serialization of the project has been in use for sending text fields.
Your question is kind of unclear on what you trying to achieve. In general, if you using binary serialization, it will convert your objects into byte array, you need to de-serialize inorder to get your object back. Below is a sample
BinaryFormatter m_formatter;
Byte[] m_stateData;
List<T> cloned_objList;
public binaryserializer(List<T> PlayersOnBench)
{
if ((!Object.ReferenceEquals(listToClone, null)) && (typeof(T).IsSerializable))
{
m_formatter = new BinaryFormatter();
using (MemoryStream stream = new MemoryStream())
{
try
{
m_formatter.Serialize(stream, PlayersOnBench);
}
catch { }
stream.Seek(0, SeekOrigin.Begin);
m_stateData = stream.ToArray();
}
}
}
public List<T> BenchStates
{
get
{
using (MemoryStream stream = new MemoryStream(m_stateData))
{
try
{
cloned_objList = (List<T>)m_formatter.Deserialize(stream);
}
catch (Exception) { }
}
return cloned_objList;
}
}

File load and adding to list

I'm basically trying to add the items from a .txt file into a listbox. The problem is that the method for loading the .txt file is in a seperate class, so I came to a point where i don`t know what to do. Any help would be greatly appreciated. Here is the class, with the file loading method:
public class BunchOfDeliverables
{
private List<Person> myPersons;
private List<Deliverable> myDeliverables;
public BunchOfDeliverables()
{
this.myPersons = new List<Person>();
this.myDeliverables = new List<Deliverable>();
}
public List<Person> Persons { get { return this.myPersons; } }
public List<Deliverable> Deliverables { get { return this.myDeliverables; } }
public void LoadPersonsFromFile(String filename)
{
StreamReader sr = null;
try
{
sr = new StreamReader(new FileStream(filename, FileMode.Open, FileAccess.Read));
String name, street, housenr, postalcode, city;
name = sr.ReadLine();
while (name != null)
{
street = sr.ReadLine();
housenr = sr.ReadLine();
postalcode = sr.ReadLine();
city = sr.ReadLine();
this.myPersons.Add(new Person(name, street, Convert.ToInt32(housenr), postalcode, city));
name = sr.ReadLine();
name = sr.ReadLine(); //and again read a line, because of the delimiter (line with the stars)
}
}
catch (IOException) { }
finally
{
if (sr != null) sr.Close();
}
}
public void LoadDeliverablesFromFile(String filename)
{
StreamReader sr = null;
try
{
sr = new StreamReader(new FileStream(filename, FileMode.Open, FileAccess.Read));
String s;
s = sr.ReadLine();
while (s != null)
{
String[] items = s.Split();
this.myDeliverables.Add(new Deliverable(Convert.ToInt32(items[0]), Convert.ToInt32(items[1]), this.myPersons[Convert.ToInt32(items[2])]));
s = sr.ReadLine();
}
}
catch (IOException) { }
finally
{
if (sr != null) sr.Close();
}
}
public void AddPerson(Person p)
{
this.myPersons.Add(p);
}
public Deliverable FindDeliverable(int id)
{
foreach (Deliverable d in this.myDeliverables)
{
if (d.ID == id)
{
return d;
}
}
return null;
}
public void AddDeliverable(Deliverable d)
{
if (FindDeliverable(d.ID) == null)
{
myDeliverables.Add(d);
}
else
{
throw new Exception("Be aware: nothing is added!!!");
}
}
AND then here is the form class (mostly empty):
public partial class Form1 : Form
{
BunchOfDeliverables d;
public Form1()
{
InitializeComponent();
d = new BunchOfDeliverables();
}
private void AddLoadedFilesToListbox_Click(object sender, EventArgs e)
{
}
Edit :
I tryed the following but again it does not work:
public partial class Form1 : Form
{
BunchOfDeliverables d;
public Form1()
{
InitializeComponent();
d = new BunchOfDeliverables();
d.LoadDeliverablesFromFile("..data/deliverables.txt");
}
private void button1_Click(object sender, EventArgs e)
{
foreach (Deliverable deliv in d.Deliverables)
{
listBox1.Items.Add(deliv);
}
}
private void Form1_Load(object sender, EventArgs e)
{
}
}
It is that simple:
BunchOfDeliverables bunchOfDeliverables = new BunchOfDeliverables();
bunchOfDeliverables.LoadPersonsFromFile(personsFile);
bunchOfDeliverables.LoadDeliverablesFromFile(deliverablesFile);
listBox.DataSource = bunchOfDeliverables.Persons;
listBox.DisplayMember = "<Whatever>";
listBox.ValueMember = "<Whatever>";
// OR
listBox.DataSource = bunchOfDeliverables.Deliverables;
listBox.DisplayMember = "<Whatever>";
listBox.ValueMember = "<Whatever>";
I don't know which list (Persons or Deliverables) do you use, so the code contains both.

How do I load multiple XML files and read them?

I've a problem. In my code I'm looking for all xml files in one directory. Finally it works but I don't know how to read them. A single one is loaded with the string xmlFile. I think I need to replace or edit that in this way that my code now that xmlFile is not only one file, but all files who are found in the directory.
What should I be doing?
namespace WindowsFormsApplication11
{
public partial class Form1 : Form
{
private const string xmlFile = "C:\Games\games.xml"; // single xml file works
public Form1()
{
this.InitializeComponent();
this.InitializeListView();
this.LoadDataFromXml();
listView.Items.AddRange(Directory.GetFiles("C:\Games\", "*.xml")
.Select(f => new ListViewItem(f))
.ToArray());
}
private void LoadDataFromXml()
{
if (File.Exists(xmlFile))
{
XDocument document = XDocument.Load(xmlFile);
if (document.Root != null)
{
foreach (XElement gameElement in document.Root.Elements("game"))
{
string gamename = gameElement.Element("gamename").Value;
string launchpath = gameElement.Element("launchpath").Value;
string uninstallpath = gameElement.Element("uninstallpath").Value;
string publisher = gameElement.Element("publisher").Value;
// check if gameElement.Element(ELEMENTNAME) is not null
Game game = new Game(gamename, launchpath, uninstallpath, publisher);
AddGameToListView(game);
}
}
}
}
private void AddGameToListView(Game game)
{
ListViewItem item = CreateGameListViewItem(game);
this.listView.Items.Add(item);
}
private ListViewItem CreateGameListViewItem(Game game)
{
ListViewItem item = new ListViewItem(game.Gamename);
item.SubItems.Add(game.Launchpath);
item.SubItems.Add(game.Uninstallpath);
item.SubItems.Add(game.Publisher);
item.Tag = game;
return item;
}
private void InitializeListView()
{
this.listView.View = View.Details;
this.listView.GridLines = true;
this.listView.MultiSelect = false;
this.listView.FullRowSelect = true;
this.listView.Columns.AddRange(new[]
{
new ColumnHeader{Text = "Gamename", Width = 200},
new ColumnHeader{Text = "Launchpath"},
new ColumnHeader{Text = "Uninstallpath"},
new ColumnHeader{Text = "Publisher"}
});
this.listView.MouseDoubleClick += ListViewOnMouseDoubleClick;
}
private void ListViewOnMouseDoubleClick(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left && this.listView.SelectedItems.Count > 0)
{
Game game = (Game)((this.listView.SelectedItems[0].Tag);
try
{
Process.Start(game.Launchpath);
}
catch (Exception ex)
{
MessageBox.Show("Can not start game.\nDetails:\n" + ex.Message, "Error", MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
}
}
}
internal class Game
{
public Game()
{
}
public Game(string gamename, string launchpath, string uninstallpath, string publisher)
{
this.Gamename = gamename;
this.Launchpath = launchpath;
this.Uninstallpath = uninstallpath;
this.Publisher = publisher;
}
public string Gamename { get; set; }
public string Launchpath { get; set; }
public string Uninstallpath { get; set; }
public string Publisher { get; set; }
}
}
UPDATE:
This is my current code. how can i send f to LoadDataFromXml ?
public Form1()
{
this.InitializeComponent();
this.InitializeListView();
this.Height = Screen.PrimaryScreen.WorkingArea.Height;
var files = Directory.GetFiles(#"C:\Games\", "*.xml").Select(f => new ListViewItem(f)).ToArray(); listView.Items.AddRange(files);
foreach (var f in files)
{
this.LoadDataFromXml(f);
}
}
private void LoadDataFromXml(//What Do I need to enter here?)
{
foreach (XElement gameElement in f.Root.Elements("game"))
{
string gamename = gameElement.Element("gamename").Value;
string launchpath = gameElement.Element("launchpath").Value;
string portablesave = gameElement.Element("portablesave").Value;
string publisher = gameElement.Element("publisher").Value;
string gameid = gameElement.Element("gameID").Value;
string update = gameElement.Element("update").Value;
// check if gameElement.Element(ELEMENTNAME) is not null
Game game = new Game(gamename, launchpath, portablesave, publisher, gameid, update);
AddGameToListView(game);
}
}
Simple use Directory functions to get all your XML files, and loop through them, by calling LoadDataFromXml for each file. Note: You will need to refactor your code a little bit.
You need to modify your LoadDataFromXml to take file as a parameter. And change your Form1 constructor to something like this
public Form1()
{
this.InitializeComponent();
this.InitializeListView();
var files = Directory.GetFiles("C:\Games\", "*.xml")
.Select(f => new ListViewItem(f))
.ToArray();
listView.Items.AddRange(files);
foreach(var f in files)
{
this.LoadDataFromXml(f);
}
}

C# how to save userinput in windows form

I'm currently trying to make a small program that store the input by the user in the textbox to a file but somehow I couldn't save the input to the file this is what I have done so far:
First Class:
class Name
{
private string SongName;
private string ArtistName;
//Constructor
public Name(string SongName, string ArtistName)
{
this.ArtistName = ArtistName;
this.SongName = SongName;
}
//Properties for SongName
public string songName
{
get { return SongName; }
set { SongName = value; }
}
//Properties for ArtistName
public string artistName
{
get { return ArtistName; }
set { ArtistName = value; }
}
}
And here is the Form1 code:
public Form1()
{
InitializeComponent();
}
private string SongName, ArtistName;
public void Registry()
{
List<Name> MusicList = new List<Name>();
MusicList.Add(new Name(SongName = txtSongName.Text , ArtistName = txtArtistName.Text)); //Add new elements to the NameClass
//Save the list
StreamWriter FileSaving = new StreamWriter("MusicList");
for (int i = 0; i < MusicList.Count; i++)
{
string sName = MusicList[i].songName;
string aName = MusicList[i].artistName;
}
FileSaving.Close();
}
private void btnEnter_Click(object sender, EventArgs e)
{
Registry();
//Set the textbox to emty so the user can enter new data
txtArtistName.Text = "";
txtSongName.Text = "";
}
In your for loop you need to actually write the values to the stream.
for (int i = 0; i < MusicList.Count i++)
{
string sName = MusicList[i].songName;
string aName = MusicList[i].artistName;
FileSaving.WriteLine(sName + ' ' + aName);
}
....You never write anything to the file.....
A quick Google got me this
Notice the call to file.WriteLine(line); also...you realize you are not creating your file with an extension, also?
Here you are creating the StreamWriter but never using it:
StreamWriter FileSaving = new StreamWriter("MusicList");
for (int i = 0; i < MusicList.Count; i++)
{
string sName = MusicList[i].songName;
string aName = MusicList[i].artistName;
}
FileSaving.Close();
strings aName and sName are assigned to but never saved.
See example here on using StreamWriter:
http://msdn.microsoft.com/en-us/library/system.io.streamwriter.aspx
using (StreamWriter writer = new StreamWriter(filePath))
{
for (int i = 0; i < MusicList.Count; i++)
{
writer.WriteLine(MusicList[i].songName + " , " + MusicList[i].artistName);
}
}
I my opinion You should use XML Serialization
here is my serialization generic class
public static class Serializer<T>
{
public static T Deserialize(string path)
{
System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(typeof(T));
System.IO.FileStream stream = null;
try
{
stream = new System.IO.FileStream(path, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read);
return (T)serializer.Deserialize(stream);
}
finally
{
if (stream != null)
{
stream.Close();
stream.Dispose();
}
}
}
public static void Serialize(string path, T obj, bool createFolder = false)
{
System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(typeof(T));
if (createFolder)
{
System.IO.Directory.CreateDirectory(System.IO.Path.GetDirectoryName(path));
}
using (System.Xml.XmlTextWriter xmlWriter = new System.Xml.XmlTextWriter(path, System.Text.Encoding.Unicode))
{
xmlWriter.Formatting = System.Xml.Formatting.Indented;
serializer.Serialize(xmlWriter, obj);
xmlWriter.Flush();
xmlWriter.Close();
}
}
}
Then in Registy Method
public void Registry()
{
List<Name> MusicList = new List<Name>();
MusicList.Add(new Name(SongName = txtSongName.Text , ArtistName = txtArtistName.Text)); //Add new elements to the NameClass
Serializer<List<Name>>.Serialize(#"C:\saved.xml", MusicList);
}
note that you must add default constructor in class Name

Categories

Resources