13 Replies - 12249 Views - Last Post: 27 June 2009 - 02:56 PM Rate Topic: -----

#1 Delta42O  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 7
  • Joined: 24-June 09

Reading from csv and storing items in array?

Posted 24 June 2009 - 02:50 PM

Hey Guys!

I am relatively new to this forum. Decided to sign up!

I have a couple of questions wich I beleive are relatively simple. I am learning C # as we speak but I need a little help.

So I have a Form with a RichTextBox that I want to fill with the information from the csv. I can get 1 line... But there are 4 and more to come. Example of this csv is as follows: FirstName,LastName,ID,Commision followed by a new line char.

Here is a short example of the code I have to add this to a collection:

 
public bool ReadCurators()
		{
			FileStream aFile = new FileStream("curators.txt", FileMode.OpenOrCreate);
			StreamReader SR = new StreamReader(aFile);
			string strLine;
			string[] strArray;
			char[] split = new char[] { ',' };
			Gallery gal = new Gallery();

			strLine = SR.ReadLine();

			try
			{
				do
				{
					strArray = strLine.Split(split);
					gal.AddCurator(strArray[0], strArray[1], strArray[2]);
					strLine = SR.ReadLine();

				} while (strLine != null);
				SR.Close();
				return true;
			}

			catch (IOException ex)
			{
				Console.WriteLine(ex.ToString());
				return false;
			}




It probably isnt the best code but I am learning so bare with me :D

And also one more thing... How would I go about listing all the "curators" from a class library? the method I have to use has a return type of void... ??? Ahhh! So complex but I LOVE IT AND WANT TO LEARN MORE!

So hopefully I am not such a noob and someone can help me out a litlle.

Thanks Guys!

Delta

This post has been edited by Delta42O: 24 June 2009 - 02:53 PM


Is This A Good Question/Topic? 0
  • +

Replies To: Reading from csv and storing items in array?

#2 lesPaul456  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 173
  • View blog
  • Posts: 729
  • Joined: 16-April 09

Re: Reading from csv and storing items in array?

Posted 24 June 2009 - 03:21 PM

What exactly is the problem?

Anyway, there is an easier way to get all the lines you need.

string[] allLines = File.ReadAllLines("curators.txt");
string[] firstNames = new string[allLines.Length];
string[] lastNames = new string[allLines.Length];
int[] ids = new int[allLines.Length];
int[] commisions = new int[allLines.Length];

for (int i = 0; i < allLines.Length; i++)
{
    string[] lineSplit = allLines[i].Split(',');
    firstNames[i] = lineSplit[0];
    lastNames[i] = linesSplit[1];
    ids[i] = Convert.ToInt32(lineSplit[2]);
    commisions[i] = Convert.ToInt32(lineSplit[3]);
}



This reads the entire file and stores each value in an array. This, though, is still not the best method...

A better method would be to create a class that stores all the data for each curator. Then, read the file, and fill in the information.

Curator.cs
public string FirstName {get; set;}
public string LastName {get; set;}
public int ID {get; set;}
public int Commision {get; set;}



ReadCurators Method
string[] allLines = File.ReadAllLines("curators.txt");
Curator[] curators = new Curator[allLines.Length];

for (int i = 0; i < allLines.Length; i++)
{
    string[] lineSplit = allLines[i].Split(',');
    curators[i] = new Curator();
    curators[i].FirstName = lineSplit[0];
    curators[i].LastName = lineSplit[1];
    curators[i].ID = Convert.ToInt32(lineSplit[2]);
    curators[i].Commision = Convert.ToInt32(lineSplit[3]);
}



These are just a few suggestions. There are still better ways if doing this, but these were just a few ideas.

Also, have you looked into using xml files? Xml files are incredibly easy to work with in C#, especially with Linq-to-Xml.

Hope this helps!
Was This Post Helpful? 1
  • +
  • -

#3 Delta42O  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 7
  • Joined: 24-June 09

Re: Reading from csv and storing items in array?

Posted 24 June 2009 - 03:33 PM

Hey!

Thanks for the reply! I already have a class library with classes for curators, artists, art pieces all with get and set properties.

This is the curators collection I have to implement the method to read from csv.
namespace CGS
{
	/// <summary>
	/// Summary description for Curators.
	/// </summary>
	public class Curators : CollectionBase
	{
		public void Add(Curator newCurator)
		{
			List.Add (newCurator);
		}
		
		public Curators()
		{
			//
			// TODO: Add constructor logic here
			//
		}

		public Curator this[int curatorIndex]
		{
			get
			{
				return (Curator)List[curatorIndex];
			}
			set
			{
				List[curatorIndex] = value;
			}
		}

		public bool ReadCurators()
		{
			FileStream aFile = new FileStream("curators.txt", FileMode.OpenOrCreate);
			StreamReader SR = new StreamReader(aFile);
			string strLine;
			string[] strArray;
			char[] split = new char[] { ',' };
			Gallery gal = new Gallery();

			strLine = SR.ReadLine();

			try
			{
				do
				{
					strArray = strLine.Split(split);
					gal.AddCurator(strArray[0], strArray[1], strArray[2]);
					strLine = SR.ReadLine();

				} while (strLine != null);
				SR.Close();
				return true;
			}

			catch (IOException ex)
			{
				Console.WriteLine(ex.ToString());
				SR.Close();
				return false;
			}
		}


	}
}



And the actual Curator class:
namespace CGS
{
	/// <summary>
	/// Summary description for Curator.
	/// </summary>
	public delegate void CommissionPaidHandler(object sender, EventArgs e);	
	
	public class Curator : Person
	{
		public event CommissionPaidHandler Changed;

		private string ID = "";
		private double commission;
		const double commRate = 0.10;

		public string CuratorID
		{
			get
			{
				return ID;
			}
			set
			{
				ID = value;
			}
		}

		public double Commission
		{
			get
			{
				return commission;
			}
			set
			{
				commission = value;
			}
		}

		public Curator()
		{
		}
		
		public Curator(string First, string Last, string curID) : base (First, Last)
		{
			ID = curID;
			commission = 0;
		}

		public string GetID()
		{
			return ID;
		}

		public double SetComm()
		{
			ArtPiece aPiece = new ArtPiece();
			aPiece.CalculateComm(commRate);
			return Convert.ToDouble(aPiece);
		}

		public override string ToString()
		{
			string curatorInformation = base.FirstName + "," + base.LastName + "," +
				CuratorID + "," + Convert.ToString(commission);
					
			return curatorInformation;
		}

		public void GetComm(double pieceCommission)
		{
			double earnedComm;
			
			if(pieceCommission > 0)
			{
				earnedComm = pieceCommission * commRate;
				commission = commission + earnedComm;
				onchangeCommission(EventArgs.Empty );
			}
		}

		// get the current EventArgs 		
		protected virtual void onchangeCommission (EventArgs e)
		{
			if (Changed != null)
				Changed(this, e);
		}

		public void ClearComm()
		{
			commission = 0;
			//clear any eventargs remaining
			onchangeCommission(EventArgs.Empty );
		}


	}
}



Now I don't know if the 2 classes I provided will be of much help but I figured it might give you a little more insight!

Thanks lespaul for your help, like I said I love learning about programming. As for xml, I havent reached that step yet. I believe it is the next thing I will look into. I want to get the hang of csv's because it seems to me like these files are still very popular.
Was This Post Helpful? 0
  • +
  • -

#4 PsychoCoder  Icon User is offline

  • Google.Sucks.Init(true);
  • member icon

Reputation: 1642
  • View blog
  • Posts: 19,853
  • Joined: 26-July 07

Re: Reading from csv and storing items in array?

Posted 24 June 2009 - 03:57 PM

Another way of accomplishing this (If you're using 3.5) is to use LINQ. Here's how I would accomplish this task. First I would create an extension method for the StreamReader Class (for best results have each item on it's own line

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml.Linq;

public static class LinqToText
{
	public static IEnumerable<string> GetAllLines(this StreamReader reader)
	{
		string line;

		//if not reader is supplied throw an Exception
		if (reader == null)
			throw new ArgumentNullException("reader");

		//otherwise we want to loop through the file and get all the curators
		while ((line = reader.ReadLine()) != null)
		{
			yield return line;
		}
	}
}




Then I would get the curators and use LINQ to iterate through them like this:

public bool ReadCurators()
{
	Gallery gal = new Gallery();
	try
	{
		using (StreamReader reader = new StreamReader("curators.txt", Encoding.GetEncoding("iso-8859-1")))
		{
			var curators = from s in LinqToText.reader.Lines()
						   select s;

			foreach (string curator in curators)
			{
				string part = curator.Split(new char[] { ',' });
				gal.Add((string)curator[0], (string)curator[1], (string)curator[2]);
			}

			return true;
		}
	}
	catch (IOException ex)
	{
		Console.WriteLine(ex.ToString());
		return false;
	}
}



Just another option for ya :)
Was This Post Helpful? 1
  • +
  • -

#5 Delta42O  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 7
  • Joined: 24-June 09

Re: Reading from csv and storing items in array?

Posted 24 June 2009 - 04:10 PM

Thanks Psycho!

If only I had C# 3.5. I'm on 2.0 visual studio 2005.

There is one more thing.

In a class library you can output to a console window. How would I output to my Form? I tried referencing System,.Windows.Foms and then tried to get a MessageBox to show up but no luck. Is it even possible to output text to any components of a form?

I have a method called GetCurators that calls ReadCurators. If ReadCurators returns true; then GetCurators will return true as well and I can call my ListCurators method. The ListCurators method returns void. When I made my prototype in console, everything was great and I could display all the curators in the collection, but now that I am making the GUI I have lost the ability to display information from the class library to a messagebox, richtextbox... Anything related to a form pretty much.

Any insight would be great!

Thanks Guys!

Delta
Was This Post Helpful? 0
  • +
  • -

#6 PsychoCoder  Icon User is offline

  • Google.Sucks.Init(true);
  • member icon

Reputation: 1642
  • View blog
  • Posts: 19,853
  • Joined: 26-July 07

Re: Reading from csv and storing items in array?

Posted 24 June 2009 - 04:10 PM

Sorry, made a mistake in ReadCurators, here's the updated code

public bool ReadCurators()
{
	Gallery gal = new Gallery();
	try
	{
		using (StreamReader reader = new StreamReader("curators.txt", Encoding.GetEncoding("iso-8859-1")))
		{
			var curators = from s in LinqToText.GetAllLines(reader)
						   select s;

			foreach (string curator in curators)
			{
				string[] part = curator.Split(new char[] { ',' });
				gal.Add((string)part[0], (string)part[1], (string)part[2]);
			}

			return true;
		}
	}
	catch (IOException ex)
	{
		Console.WriteLine(ex.ToString());
		return false;
	}
}



Sorry about that :blush:
Was This Post Helpful? 0
  • +
  • -

#7 lesPaul456  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 173
  • View blog
  • Posts: 729
  • Joined: 16-April 09

Re: Reading from csv and storing items in array?

Posted 24 June 2009 - 04:13 PM

View PostDelta42O, on 24 Jun, 2009 - 05:10 PM, said:

Thanks Psycho!

If only I had C# 3.5. I'm on 2.0 visual studio 2005.

There is one more thing.

In a class library you can output to a console window. How would I output to my Form? I tried referencing System,.Windows.Foms and then tried to get a MessageBox to show up but no luck. Is it even possible to output text to any components of a form?

I have a method called GetCurators that calls ReadCurators. If ReadCurators returns true; then GetCurators will return true as well and I can call my ListCurators method. The ListCurators method returns void. When I made my prototype in console, everything was great and I could display all the curators in the collection, but now that I am making the GUI I have lost the ability to display information from the class library to a messagebox, richtextbox... Anything related to a form pretty much.

Any insight would be great!

Thanks Guys!

Delta


Could you post the code that you are using to display the info?
Was This Post Helpful? 0
  • +
  • -

#8 Delta42O  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 7
  • Joined: 24-June 09

Re: Reading from csv and storing items in array?

Posted 24 June 2009 - 04:22 PM

public void ListCurators()
		{
			Console.WriteLine("ListCurators method called");
			foreach (Curator curator in curators)
			{
				Console.WriteLine("Name: " + curator.FirstName + " " + curator.LastName + ", " + curator.CuratorID);
			}

		}



That works great in the console prototype but I can't figure out how to pass the info from the for loop to a richtextbox or a messagebox.
In my UML my ListCurators methos shows: + ListCurators() : void

I know I can return a string value but it will only return 1 string and not the other 3 with it and well based on my UML it has to be void.

Thank you guys so much for your assistance. I really appreciate it!

Delta
Was This Post Helpful? 0
  • +
  • -

#9 lesPaul456  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 173
  • View blog
  • Posts: 729
  • Joined: 16-April 09

Re: Reading from csv and storing items in array?

Posted 24 June 2009 - 04:28 PM

*EDIT* OOPS! I miss read you post :stupid: *EDIT*

You could make the ListCurators method take a rich text box as a paramter.

public void ListCurators(ref RichTextBox richTextBox)
{
    foreach (Curator curator in curators)   
   {        
        richTextBox.Text += "Name: " + curator.FirstName + " " + curator.LastName + ", " + curator.CuratorID + "\n";    }
    }


This post has been edited by lesPaul456: 24 June 2009 - 04:39 PM

Was This Post Helpful? 1
  • +
  • -

#10 Delta42O  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 7
  • Joined: 24-June 09

Re: Reading from csv and storing items in array?

Posted 24 June 2009 - 04:38 PM

View PostlesPaul456, on 24 Jun, 2009 - 03:28 PM, said:

The code for a message box:

public void ListCurators()
{
    foreach (Curator curator in curators)
    {
        MessageBox.Show("Name: " + curator.FirstName + " " + curator.LastName + ", " + curator.CuratorID);
    }
}



Code for rich text box:

public void ListCurators()
{
    foreach (Curator curator in curators)
    {
        richTextBox.Text += "Name: " + curator.FirstName + " " + curator.LastName + ", " + curator.CuratorID + "\n";
    }
}



*EDIT* I added "\n" to the end so that each curator would be on a new line. *EDIT*


Thats exactly what I did but when I run the app, it wont show up... On my windows form my richtextbox is labeled as rtbinfo. How can I send the output from the for loop to that specific box?

Thanks again,

Delta

BTW: I am stepping out so dont think i am ignoring your amazing help!
Was This Post Helpful? 0
  • +
  • -

#11 lesPaul456  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 173
  • View blog
  • Posts: 729
  • Joined: 16-April 09

Re: Reading from csv and storing items in array?

Posted 24 June 2009 - 04:40 PM

Sorry, I edited my last post as you were replying. Let me know if the modified post helps.
Was This Post Helpful? 0
  • +
  • -

#12 Delta42O  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 7
  • Joined: 24-June 09

Re: Reading from csv and storing items in array?

Posted 24 June 2009 - 08:49 PM

As of right now, with the reference to the richtextbox, nothing is showing up in my rich text box on my form. I'm stumped!

So far nothing, but the help is extremely helpful. I have no clue as to why this isn't working but I am going to keep trying. It's like the class library call's my method but won't return any of the information.

Once again thanks alot everyone who is helping me out!

Delta
Was This Post Helpful? 0
  • +
  • -

#13 Zavior  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 1
  • Joined: 26-June 09

Re: Reading from csv and storing items in array?

Posted 26 June 2009 - 04:36 PM

By default, Console apps do not reference System.Windows.Forms, which is where the MessageBox.Show method lives. You can add the reference so you can use MessageBox.Show.
Was This Post Helpful? 0
  • +
  • -

#14 Delta42O  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 7
  • Joined: 24-June 09

Re: Reading from csv and storing items in array?

Posted 27 June 2009 - 02:56 PM

Thank ALL OF YOU!

Now I can actually get my dll to show up some info on my form!

The only thing that still is not working is reading from my csv and entering the curators line by line!

I really do not know what to do. It still only gives me 1 line no matter what method I try.

Thanks again guys!

Delta
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1