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
Related
I have a blocking collection which gets filled with data by some app1.
I have subscribed to that blocking collection and need to write a file with below case,
start writing a file .
if the file size crossed 100kb, close the first file and starts a new file.
and if there is no data coming from app1, lets say for 1 minute, then close the file.
Currently with below code, I'm only able to write per blocking collection into per file, how to proceed with my above requirement, please suggest.
class Program
{
private static BlockingCollection<Message> messages = new BlockingCollection<Message>();
private static void Producer()
{
int ctr = 1;
while (true)
{
messages.Add(new Message { Id = ctr, Name = $"Name-{ctr}" });
Thread.Sleep(1000);
ctr++;
}
}
private static void Consumer()
{
foreach (var message in messages.GetConsumingEnumerable())
{
Console.WriteLine(JsonConvert.SerializeObject(message));
using (var streamWriter = File.CreateText(Path.Combine(#"C:\TEMP", $"File-{ DateTime.Now.ToString("yyyyMMddHHmmssfff")}.json")))
{
using (var writer = new JsonTextWriter(streamWriter))
{
writer.Formatting = Formatting.Indented;
writer.WriteStartObject();
writer.WritePropertyName("Data");
writer.WriteStartArray();
writer.WriteRawValue(JsonConvert.SerializeObject(message));
writer.WriteEndArray();
writer.WriteEndObject();
}
}
}
}
static void Main(string[] args)
{
var producer = Task.Factory.StartNew(() => Producer());
var consumer = Task.Factory.StartNew(() => Consumer());
Console.Read();
}
}
This will take the messages with any size and divided it to a different JSON file. You need to specify the size using maxchar. before that, you have to check the size of the last file like this and you have to pass the same file name and the new size if else create a new file and divide the message.
using System;
using System.IO;
using System;
using System.Threading;
using System.Threading.Tasks;
using System.Collections.Concurrent;
using System.Collections;
using Newtonsoft.Json;
using System.Runtime.Remoting.Messaging;
using System.Text;
namespace Program
{
class Program
{
public static string last_path = "";
public static readonly string BYE = "bye";
private static BlockingCollection<Message> messages = new BlockingCollection<Message>();
private static void Producer()
{
int ctr = 1;
while (true)
{
messages.Add(new Message { Id = ctr, Name = $"Name-{ctr}" });
Thread.Sleep(1000);
ctr++;
}
}
private static void Consumer()
{
foreach (var message in messages.GetConsumingEnumerable())
{
Console.WriteLine(JsonConvert.SerializeObject(message));
string json = JsonConvert.SerializeObject(message);
int maxchar = 102400;
if (last_path != "")
{
long length = new FileInfo(last_path).Length;
if (length < maxchar)
{
maxchar = maxchar - unchecked((int)length);
dividefile(last_path, maxchar, json);
}
else
{
dividefile("", maxchar, json);
}
}
else
{
dividefile("", maxchar, json);
}
}
}
public static void dividefile(string path, int maxchar, string message)
{
//FileStream fileStream = new FileStream(yourfile, FileMode.Open, FileAccess.Read);
byte[] byteArray = Encoding.UTF8.GetBytes(message);
MemoryStream stream = new MemoryStream(byteArray);
using (StreamReader streamReader = new StreamReader(stream))
{
Int64 x1 = stream.Length;
char[] fileContents = new char[maxchar];
int charsRead = streamReader.Read(fileContents, 0, maxchar);
// Can't do much with 0 bytes
if (charsRead == 0)
throw new Exception("File is 0 bytes");
while (charsRead > 0)
{
x1 = x1 - maxchar;
if (x1 > 0)
{
string s = new string(fileContents);
if (path == "")
{
last_path = Path.Combine(#"C:\TEMP", $"File-{ DateTime.Now.ToString("yyyyMMddHHmmssfff")}.json");
path = "";
}
else
{
last_path = path;
}
AppendTransaction(last_path, s);
charsRead = streamReader.Read(fileContents, 0, maxchar);
}
else
{
int m = (int)(((x1 + maxchar) % maxchar));
string messagechunk = new string(fileContents, 0, m);
if (path == "")
{
last_path = Path.Combine(#"C:\TEMP", $"File-{ DateTime.Now.ToString("yyyyMMddHHmmssfff")}.json");
path = "";
}
else
{
last_path = path;
}
AppendTransaction(last_path, messagechunk);
charsRead = streamReader.Read(fileContents, 0, m);
}
}
}
}
private static void AppendTransaction(string path , string transaction)
{
string filename = path;
bool firstTransaction = !File.Exists(filename);
JsonSerializer ser = new JsonSerializer();
ser.Formatting = Formatting.Indented;
ser.TypeNameHandling = TypeNameHandling.Auto;
using (var fs = new FileStream(filename, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.Read))
{
Encoding enc = firstTransaction ? new UTF8Encoding(true) : new UTF8Encoding(false);
using (var sw = new StreamWriter(fs, enc))
using (var jtw = new JsonTextWriter(sw))
{
if (firstTransaction)
{
sw.Write("[");
sw.Flush();
}
else
{
fs.Seek(-Encoding.UTF8.GetByteCount("]"), SeekOrigin.End);
sw.Write(",");
sw.Flush();
}
ser.Serialize(jtw, transaction);
sw.Write(']');
}
}
}
static void Main(string[] args)
{
var producer = Task.Factory.StartNew(() => Producer());
var consumer = Task.Factory.StartNew(() => Consumer());
Console.Read();
}
class Message
{
public int ProductorThreadID { get; set; }
public int CustomerThreadID { get; set; }
public string key { get; set; }
public string content { get; set; }
public string Name { get; internal set; }
public int Id { get; internal set; }
public bool endThread()
{
return string.Compare(key, Program.BYE) == 0;
}
public string ToString(bool isProductor)
{
return string.Format("{0} Thread ID {1} : {2}", isProductor ? "Productor" : "Customer",
isProductor ? ProductorThreadID.ToString() : CustomerThreadID.ToString(),
content);
}
}
}
}
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 { }
}
}
}
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.
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.
I know this is a very simple and basic question but I would like to know how to fix this. I got a problem in serializing the object from the datagrdiview.
This line is not working for me in the
if (dataGridView1 != null)
_example.Details = dataGridView1.DataBindings; // Not Working.
Please tell me what is the mistake I'm doing here...! Thank you.
private void button3_Click(object sender, EventArgs e) //Read
{
XmlSerializer _serializer = new XmlSerializer(typeof(XMLExample));
XMLExample _example = new XMLExample();
// Read file.
using (TextReader textReader = new StreamReader(#"C:\test\testserialization.xml"))
{
_example = (XMLExample)_serializer.Deserialize(textReader);
textReader.Close();
}
textBox1.Text = _example.ID;
textBox2.Text = _example.Initial;
dataGridView1.DataSource = _example.Details;
}
private void button2_Click(object sender, EventArgs e) //Write
{
XmlSerializer _serializer = new XmlSerializer(typeof(XMLExample));
XMLExample _example = new XMLExample();
_example.ID = textBox1.Text;
_example.Initial = textBox2.Text;
List<Detail> _source = new List<Detail>();
for (int i = 0; i < 10; i++)
{
_source.Add(new Detail
{
FirstName = "Name_" + i,
LastName = "Surname_" + i,
Section = "section_"+i,
});
}
dataGridView1.DataSource = _source;
if (dataGridView1 != null && dataGridView1.DataSource != null)
_example.Details = (List<Detail>)dataGridView1.DataSource;
using (TextWriter textWriter = new StreamWriter(#"C:\test\testserialization.xml"))
{
_serializer.Serialize(textWriter, _example);
textWriter.Close();
}
}
The class file:
[Serializable]
public class StudentInfo : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public string UserID { get; set; } // Textbox1
public string Department { get; set; } // Textbox2
public List<Detail> Details { get; set; }
}
[Serializable]
public class Detail // Datagridview1
{
[XmlElement("FirstName")] //Datagridview
public string FirstName { get; set; }
[XmlElement("LastName")] //Datagridview
public string LastName { get; set; }
[XmlElement("Section")] //Datagridview
public string Section { get; set; }
}
Try this:
if (dataGridView1 != null && dataGridView1.DataSource != null) test.Details = (List<Detail>)dataGridView1.DataSource;
Sample code with assignment List<Detail> to property DataSource of DataGridView object (add this code in constructor):
List<Detail> _source = new List<Detail>();
for (int i = 0; i < 10; i++)
{
_source.Add(new Detail
{
FirstName = "Name_" + i,
LastName = "Surname_" + i,
Section = "Section_" + i
});
}
dataGridView1.DataSource = _source;
You must serilaize not dataGridView, and DataTable or DataSource
Example:
XmlSerializer ser = new XmlSerializer(typeof(DataTable));
DataTable dt = new DataTable("data");
TextWriter writer = new StreamWriter(Application.StartupPath+"\\"+fname+".xml");
ser.Serialize(writer, dt);
writer.Close();