Hi i need to save the "pri1" variable to a class variable so other methods of the same class would be able to access.
in between these lines
"pri1.Remove(last);
foreach (string item in pri1)"
void downloader_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
if (e.Error == null)
{
Stream responseStream = e.Result;
StreamReader responseReader = new StreamReader(responseStream);
string response = responseReader.ReadToEnd();
string[] split1 = Regex.Split(response, "},{");
List<string> pri1 = new List<string>(split1);
pri1.RemoveAt(0);
string last = pri1[pri1.Count() - 1];
pri1.Remove(last);
foreach (string item in pri1)
{
string abc = "[{" + item + "}]";
byte[] buf = System.Text.Encoding.UTF8.GetBytes(abc);
MemoryStream ms = new MemoryStream(buf);
JsonArray users = (JsonArray)JsonArray.Load(ms);
var members = from member in users
//where member["SEARCHVAL"]
select member;
foreach (JsonObject member in members)
{
string schname = member["SEARCHVAL"];
string axisX = member["X"];
string axisY = member["Y"];
// Do something...
string jsonCoordinateString = "{'Coordinates':[{'X':" + axisX + ",'Y':" + axisY + "}]}";
CustomCoordinateList coordinateList = DeserializeJson<CustomCoordinateList>(jsonCoordinateString);
GraphicsLayer graphicsLayer = MyMap.Layers["MyGraphicsLayer_Primary"] as GraphicsLayer;
for (int i = 0; i < coordinateList.Coordinates.Count; i++)
{
Graphic graphic = new Graphic()
{
Geometry = new MapPoint(coordinateList.Coordinates[i].X, coordinateList.Coordinates[i].Y),
Symbol = i > 0 ? PrimarySchoolMarkerSymbol : PrimarySchoolMarkerSymbol
};
graphic.Attributes.Add("PrimarySchool", schname);
graphicsLayer.Graphics.Add(graphic);
}
}
}
}
}
You need to add a field to the class:
List<string> myField;
You can then use the field as a variable anywhere in the class.
Assuming there is a field in the class that can store the List<string> type
this.VariableName = pri1;
If there isn't a variable in the class and you haven't defined it your self you'll need to subclass and add it.
Related
I want to make a combo box like this:
But the boxes should not be hardcoded they should come from a text file like this:
Addition of data in text file should result in addition of combo Boxes. Also each comboBox should have the same list of options in it which are 1,2,3,4
I made the following class to read and write the text file, but I couldn't find any resources in the internet to turn these text files to combo Box.
public static string ReadFromTextFile(string path)
{
if (File.Exists(path))
{
string data;
using (StreamReader r = new StreamReader(path))
{
data = r.ReadToEnd();
}
if (data != "")
{
data = "[" + data + "]";
}
return data;
}
return null;
}
public static void WriteToTextFile(string path, string data, bool append = true, int count = 1)
{
if (!File.Exists(path))
{
var file = File.Create(path);
file.Close();
}
using (StreamWriter writer = new StreamWriter(path, append: append))
{
if (!append)
{
//remove opening bracket "[" from data passed
data = data.Trim().Substring(1, data.Trim().Length - 1);
//remove last bracket "]" from data passed
data = data.Trim().Substring(0, data.Trim().Length - 1);
}
if (count != 0)
{
data = data + ",";
}
writer.WriteLine(data);
}
}
public static DataTable ConvertToDataTable<T>(IList<T> data)
{
PropertyDescriptorCollection properties =
TypeDescriptor.GetProperties(typeof(T));
DataTable table = new DataTable();
foreach (PropertyDescriptor prop in properties)
table.Columns.Add(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType);
if (data != null)
{
foreach (T item in data)
{
DataRow row = table.NewRow();
foreach (PropertyDescriptor prop in properties)
row[prop.Name] = prop.GetValue(item) ?? DBNull.Value;
table.Rows.Add(row);
}
}
return table;
}
I don't have visual studio available now. So, I'll give you the way forward.
Read the line and split it into string array.
string[] arr= line.Split(",");
The first one (say Food) is the heading and the remaining are values.
Loop through the array.
for (int i=1;i<= arr.Length;i++)
{
}
Add it to the combobox items like cbo.Items.Add(arr[i]).
Loop through the lines in the file and you get the desired output.
You can use the string "Food"/"Water" as the Name property of the ComboBox to identify the each ComboBox.
Besides, note that should set a different Location for each ComboBox.
private void buttonCreateComboBox_Click(object sender, EventArgs e)
{
int locationX = 50;
int locationY = 10;
string line;
System.IO.StreamReader file =
new System.IO.StreamReader(#"C:\Users\Administrator\Desktop\test.txt");
while ((line = file.ReadLine()) != null)
{
// Remove the extra ','
string comboName = line.Substring(0, line.Length - 1);
ComboBox comboBox = new ComboBox();
comboBox.Name = comboName;
comboBox.Items.AddRange(new object[] { 1, 2, 3, 4 });
comboBox.Location = new Point(locationX, locationY);
this.Controls.Add(comboBox);
Label label = new Label();
label.Text = comboName;
label.Location = new Point(0, locationY);
this.Controls.Add(label);
locationY += 30;
}
file.Close();
}
If you want to access a specific ComboBox, you can call Control.ControlCollection.Find(String, Boolean) Method to get it.
private void buttonGetComboWaterText_Click(object sender, EventArgs e)
{
ComboBox comboWater = (ComboBox)this.Controls.Find("Water", true)[0];
MessageBox.Show(comboWater.Text);
}
Without going into details (don't know why you need DataTable etc.) I will answer your main question from title.
This is how my textfile looks, no need for comma if you read line by line:
public void ReadFromTextFile(string path)
{
if (File.Exists(path))
{
using (StreamReader r = new StreamReader(path))
{
String line;
while ((line = r.ReadLine()) != null)
{
CreateComboBox(line.ToString());
}
}
}
}
public void CreateComboBox(string definition)
{
var combo = new ComboBox();
combo.Name = definition;
combo.Items.AddRange(new object[] { "1", "2", "3", "4" });
var label = new Label();
label.Text = definition;
this.flowLayoutPanel1.Controls.Add(label);
this.flowLayoutPanel1.Controls.Add(combo);
}
private void Form1_Load(object sender, EventArgs e)
{
ReadFromTextFile(#"c:\temp\MyTest.txt");
}
Use File.ReadAllLines(...) to short the txt read.
Point to control the position.
Attaches a delegate to SelectedIndexChanged that I imagine you will need for the next step.
private void Form1_Load(object sender, EventArgs e)
{
var lines = File.ReadAllLines(#"src.txt").Select(str => str.Replace(",", "")).ToList();
Label lbl, lastLbl = null;
ComboBox combo, lastCombo = null;
for (int i = 0; i < lines.Count(); i++)
{
lbl = new Label();
lbl.Text = lines[i];
if (i > 0) // adjust position
lbl.Location = new Point(lastLbl.Location.X, lastLbl.Location.Y + lastLbl.Height);
this.Controls.Add(lbl);
lastLbl = lbl;
combo = new ComboBox();
combo.DataSource = new List<int>() { 1, 2, 3, 4 };
if (i > 0) // adjust position
combo.Location = new Point(lastCombo.Location.X, lastCombo.Location.Y + lastCombo.Height);
else
combo.Location = new Point(lbl.Width + 5, 0);
//combo.SelectedIndexChanged += (s, a) => { }; // action you may need
this.Controls.Add(combo);
lastCombo = combo;
}
}
I'm fairly new to C# and im writing a rental vehicle management system. I'm trying to retrieve all lines from a CSV file that is set up like this:
[Registration][Grade][Make][Model][Year][NumSeats][Transmission][Fuel][GPS][SunRoof][DailyRate][Colour]
[123ABC][Economy][Toyota][Camry][2005][5][Automatic][Petrol][No][No][30][White]
[234BCD][Economy][Ford][Focus][2012][5][Automatic][Petrol][Yes][No][45][Blue]
[987ZYX][Economy][Holden][Cruise][2016][5][Manual][Diesel][Yes][No][60][Red]
and then iterate it through a for loop before it's sent to another method.
In the following method beyond the one shown, it's being put into an ArrayList so that the values retrieved can be searched for by the user in the program.
I'm stuck on the for loop as it gives me an error on the vehicles1.Length; saying that vehicles1 is a use of an unassigned local variable. I don't know if initializing the array is my problem, because I've tried that and it gives me no errors but the program just breaks.
void setUpVehicles(out Fleet fleetVehicles)
{
const char DELIM = ',';
Vehicle veh = new Vehicle();
FileStream inFile = new FileStream(FILENAME3, FileMode.Open, FileAccess.Read);
StreamReader reader = new StreamReader(inFile);
string recordIn;
string[] vehicles1;
recordIn = reader.ReadLine();
while (recordIn != null)
{
string year = veh.Year.ToString();
string seats = veh.NumSeats.ToString();
string gps = veh.GPS.ToString();
string sunRoof = veh.SunRoof.ToString();
string dailyRate = veh.DailyRate.ToString();
vehicles1 = recordIn.Split(DELIM);
veh.Registration = vehicles1[0];
veh.Grade = vehicles1[1];
veh.Make = vehicles1[2];
veh.Model = vehicles1[3];
year = vehicles1[4];
seats = vehicles1[5];
veh.Transmission = vehicles1[6];
veh.Fuel = vehicles1[7];
gps = vehicles1[8];
sunRoof = vehicles1[9];
dailyRate = vehicles1[10];
veh.Colour = vehicles1[11];
}
fleetVehicles = new Fleet();
for (int i = 0; i < vehicles1.Length; i++)
{
fleetVehicles.insertVehicle(vehicles1[i]);
}
}
IEnumerable<Vehicle> setUpVehicles(string fileName)
{
using(var reader = new StreamReader(fileName))
using(var parser = new Microsoft.VisualBasic.TextFieldParser(reader))
{
parser.TextFieldType = Microsoft.VisualBasic.FileIO.FieldType.Delimited;
parser.Delimiters = new string[] {","};
string[] row;
while(!parser.EndOfData)
{
row = parser.ReadFields();
var vehicle = new Vehicle {
Registration = row[0],
Grade = row[1],
Make = row[2],
Model = row[3],
Year = row[4],
NumSeats = row[5],
Transmission = row[6],
Fuel = row[7],
GPS = row[8],
SunRoo = row[9],
DailyRate = row[10],
Colour = row[11]
};
yield return vehicle;
}
}
}
Then you would call it to make a fleet like this:
var fleetVehicles = new Fleet();
foreach(var vehicle in setUpVehicles(FILENAME3))
{
feetVehicles.insertVehicles(vehicle);
}
There are two CSV files I am looking to consolidate into 1.
A.CSV
WBS Element,Purchasing Document,Purchase order text,Val/COArea Crcy
ABC123,,,75000
ABC124,4200028630,Service,1069.2
ABC124,4200041490,Service,25518.24
ABC124,4200041490,Service,-1890.24
ABC126,4200028630,Service,2268
ABC126,4200028630,Service,-2268
ABC126,4200029435,Service,25149.65
ABC137,,,4146.2
B.CSV
WBS Element,Ref Document Number,Val/COArea Crcy,Name
ABC124,1000060610,0,Slab Locates & Steel Differential
ABC124,1000081223,0,NOCN339A&3921
ABC124,1000081223,0,Slab Locates & Steel Differential
ABC126,1000067757,0,Structural Steel
ABC 137,4200041490,0,Service
ABC 137,4200028630,5393.52,Service
ABC 137,4200029435,0,Service
I want to make 1 CSV file that combines both of these. The lines starting with WBS Element are joined together. The WBS Elements from each file are then placed on the same line if they match. If A has a WBS Element B does not, then the section for B is just "," and vice versa.
Sample target output:
WBS Element,Purchasing Document,Purchase order text,Val/COArea Crcy,WBS Element,Ref Document Number,Val/COArea Crcy,Name
ABC123,,,75000,,,,
ABC124,4200028630,Service,1069.2,ABC124,1000060610,0,Slab Locates & Steel Differential
I have the following code:
static void Main(string[] args)
{
StreamReader a = new StreamReader(#"Input\a.csv");
StreamReader b = new StreamReader(#"Input\b.csv");
StreamWriter output = new StreamWriter(#"Output\output.csv");
Dictionary<string, string> Adict = new Dictionary<string, string>();
Dictionary<string, string> Bdict = new Dictionary<string, string>();
output.WriteLine(a.ReadLine() + "," + b.ReadLine());
while (!a.EndOfStream && !b.EndOfStream)
{
//section for A
List<string> atempList = new List<string>();
string atempString;
string Aline = a.ReadLine();
string[] Atokens = Aline.Split(','); //split the line into array
foreach (string s in Atokens)
atempList.Add(s); //add each string in token array to tempList
atempList.Remove(Atokens[0]); //remove Dict Key from tempList
StringBuilder d = new StringBuilder();
if (!Adict.ContainsKey(Atokens[0]))
{
foreach (string s in atempList)
d.Append(s + ","); //rejoin tempList into a string with ","
d.Append("\n"); //add a linebreak to end of templist string
Adict.Add(Atokens[0], d.ToString()); //Add line to dictionary with Key
}
else //Adict does contain key... need to remove Key and add bigger string
{
List<string> removeKey = new List<string>(); //temporary list
foreach (string s in Atokens)
removeKey.Add(s); //create a new list from the token array
removeKey.Remove(Atokens[0]); //remove the key from the removeKey list
atempString = Adict[Atokens[0]]; //temporary string is what's already in dictionary
Adict.Remove(Atokens[0]); //remove the Key + Value from dictionary.
Adict.Add(Atokens[0], d.Append(atempString + Aline + "\n").ToString()); // string.Concat(tempString, ",", line));
}
//section for B
List<string> btempList = new List<string>();
string btempString;
string Bline = b.ReadLine();
string[] Btokens = Bline.Split(',');
foreach (string s in Btokens)
btempList.Add(s);
btempList.Remove(Btokens[0]);
StringBuilder f = new StringBuilder();
if (!Bdict.ContainsKey(Btokens[0]))
{
foreach (string s in btempList)
f.Append(s + ",");
f.Append("\n");
Bdict.Add(Btokens[0], f.ToString());
}
else
{
List<string> removeKey = new List<string>();
foreach (string s in Btokens)
removeKey.Add(s);
removeKey.Remove(Atokens[0]);
btempString = Bdict[Btokens[0]];
Bdict.Remove(Btokens[0]);
Bdict.Add(Btokens[0], f.Append(btempString + Bline + "\n").ToString());
}
}
output.Close();
// Console.ReadLine();
}
}
I am stuck now I dont know how to look through each Dictionary and compare keys, then join (insert?) just the line that has a matching key.
first of all, I think you should make a class to use this.
The class I made for this problem is really simple:
class WbsElement
{
public string PurchasingDocument;
public string PurchaseOrderText;
public string ValCoAreaCrcyA;
public string ValCoAreaCrcyB;
public string RefDocumentNumber;
public string Name;
}
It has some attirbutes that you can use to store the data.
Then I took your code and changed it to this:
private static void Main(string[] args)
{
StreamReader a = new StreamReader(#"A.CSV");
StreamReader b = new StreamReader(#"B.CSV");
StreamWriter output = new StreamWriter(#"output.csv");
Dictionary<string, WbsElement> newDict = new Dictionary<string, WbsElement>();
output.WriteLine(a.ReadLine() + "," + b.ReadLine());
while (!a.EndOfStream && !b.EndOfStream)
{
//section for A
string Aline = a.ReadLine();
string[] Atokens = Aline.Split(','); //split the line into array
if (newDict.ContainsKey(Atokens[0]))
{
newDict[Atokens[0]].PurchasingDocument = Atokens[1];
newDict[Atokens[0]].PurchaseOrderText = Atokens[2];
newDict[Atokens[0]].ValCoAreaCrcyA = Atokens[3];
}
else
{
WbsElement elementToAdd = new WbsElement();
elementToAdd.PurchasingDocument = Atokens[1];
elementToAdd.PurchaseOrderText = Atokens[2];
elementToAdd.ValCoAreaCrcyA = Atokens[3];
newDict.Add(Atokens[0], elementToAdd);
}
}
while (!b.EndOfStream)
{
//section for B
string Bline = b.ReadLine();
string[] Btokens = Bline.Split(',');
if (newDict.ContainsKey(Btokens[0]))
{
newDict[Btokens[0]].RefDocumentNumber = Btokens[1];
newDict[Btokens[0]].ValCoAreaCrcyB = Btokens[2];
newDict[Btokens[0]].Name = Btokens[3];
}
else
{
WbsElement elementToAdd = new WbsElement();
elementToAdd.RefDocumentNumber = Btokens[1];
elementToAdd.ValCoAreaCrcyB = Btokens[2];
elementToAdd.Name = Btokens[3];
newDict.Add(Btokens[0], elementToAdd);
}
}
foreach (KeyValuePair<string, WbsElement> keyValuePair in newDict)
{
output.WriteLine(string.Format("{0},{1},{2},{3},{4},{5},{6},{7}", keyValuePair.Key, keyValuePair.Value.PurchasingDocument,
keyValuePair.Value.PurchaseOrderText, keyValuePair.Value.ValCoAreaCrcyA,
keyValuePair.Key,
keyValuePair.Value.RefDocumentNumber, keyValuePair.Value.ValCoAreaCrcyB,
keyValuePair.Value.Name));
}
output.Close();
// Console.ReadLine();
}
I make a new dictionary that stores the key + one instance of the class I made.
When I find the same key again, I just add the information to the class.
On the end of the application I just flush all the correct data to the output stream.
The class is the key to making this easy.
In case you want it generic for different length of data input, you could use this:
private static void Main(string[] args)
{
StreamReader a = new StreamReader(#"A.CSV");
StreamReader b = new StreamReader(#"B.CSV");
StreamWriter output = new StreamWriter(#"output.csv");
Dictionary<string, List<string>> newDict = new Dictionary<string, List<string>>();
string aLine = a.ReadLine();
int aLength = aLine.Split(',').Count();
output.WriteLine(aLine + "," + b.ReadLine());
while (!a.EndOfStream && !b.EndOfStream)
{
//section for A
string Aline = a.ReadLine();
string[] Atokens = Aline.Split(','); //split the line into array
if (newDict.ContainsKey(Atokens[0]))
{
for (int i = 0; i < Atokens.Length; i++)
{
newDict[Atokens[0]][i] = Atokens[i];
}
}
else
{
List<string> listToAdd = new List<string>();
for (int i = 0; i < Atokens.Length; i++)
{
listToAdd.Add(Atokens[i]);
}
newDict.Add(Atokens[0], listToAdd);
}
}
while (!b.EndOfStream)
{
//section for B
string Bline = b.ReadLine();
string[] Btokens = Bline.Split(',');
if (newDict.ContainsKey(Btokens[0]))
{
if (newDict[Btokens[0]].Count > aLength)
{
for (int i = 0; i < Btokens.Length; i++)
{
newDict[Btokens[0]][i + aLength] = Btokens[i];
}
}
else
{
for (int i = 0; i < Btokens.Length; i++)
{
newDict[Btokens[0]].Add(Btokens[i]);
}
}
}
else
{
List<string> listToAdd = new List<string>(aLength);
listToAdd.AddRange(Btokens);
newDict.Add(Btokens[0], listToAdd);
}
}
foreach (KeyValuePair<string, List<string>> keyValuePair in newDict)
{
string outputLine = string.Empty;
foreach (string s in keyValuePair.Value)
{
if (outputLine != string.Empty)
{
outputLine += ",";
}
outputLine += s;
}
output.WriteLine(outputLine);
}
output.Close();
// Console.ReadLine();
}
It uses a list to keep track of input data.
I am getting the object reference error in this line:
emp[count].emp_id = int.Parse(parts[0]);
in this code
this program to read from file and store in array of object
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public class employees
{
public int emp_id;
public string firstName;
public string lastName;
public double balance;
}
private void btnOpen_Click(object sender, EventArgs e)
{
OpenFileDialog file = new OpenFileDialog();
DialogResult result = file.ShowDialog();
if (result == DialogResult.Cancel) return;
string fileName = file.FileName;
StreamReader reader = new StreamReader(fileName);
string[] lines = File.ReadAllLines(fileName);
int emp_count = lines.Count<string>();
employees[] emp = new employees[emp_count];
int count = 0;
foreach (string line in lines)
{
string[] parts = new string[4];
parts = line.Split(',');
**emp[count].emp_id = int.Parse(parts[0]);**
emp[count].firstName = parts[1];
emp[count].lastName = parts[2];
emp[count].balance = double.Parse(parts[3]);
count++;
txtGet.Text += emp[count].emp_id + " " + emp[count].firstName + " " + emp[count].lastName + " " + emp[count].balance + " \n ";
}
You need to initialise emp[count] to something.
You can do this by adding the following:
foreach (string line in lines)
{
emp[count] = new employees();
string[] parts = new string[4];
//....
}
When you call employees[] emp = new employees[emp_count]; you initilise emp to an array of employees with the length of emp_count.
emp[0] = null;
emp[1] = null;
//etc.
Each element inside emp also needs to be instantiated before you can use it.
emp[0] has not been initialized. Class employees is a nullable type, which means arrays made of it are initialized to nulls. Initialize emp[count] to new employees.
BTW, "employees" is a strange name for a class that holds a single employee. I think it should be called Employee, then it makes sens to declare your array like this:
`Employee[] employees = new Employee[emp_count];`
I am trying to retrieve multiple images and text through data binding, but I only manage to retrieve only the first text in isolated storage(code below).
Is it possible to retrieve multiple text through data binding into a ListBox?
string imageFileName = App.imagePath;
string a;
object b;
sting h;
int i;
string noteSeparate;
private void Library_Loaded(object sender, RoutedEventArgs e)
{
if (MainListBox.Items.Count == 0)
{
//To save the separated note by '^'
string[] noteSeparated;
//Read the file and display it line by line.
IsolatedStorageFile myStore = IsolatedStorageFile.GetUserStoreForApplication();
//Read the note saved in myFile.txt
StreamReader readFile = new StreamReader(new IsolatedStorageFileStream("ViewFolder\\myFile.txt", FileMode.Open, myStore));
try
{
String fileText = readFile.ReadLine();
//noteSeparated is the variable that save the retrieve note from myFile.txt and is noteSeparated by '^'
noteSeparated = fileText.Split(new char[] { '^' });
for (i = 0; i < noteSeparated.Length; i = i + 3)
{
noteSeparate = noteSeparated[i];
a = noteSeparate;
break;
}
h = a;
readFile.Close();
}
catch (Exception)
{
noNoteBlock.Visibility = Visibility.Visible;
}
}
string imageFolder = "imageFolder";
var isoFile = IsolatedStorageFile.GetUserStoreForApplication();
// Check if directory exists
if (!isoFile.DirectoryExists(imageFolder))
{
//isoFile.CreateDirectory(imageFolder);
throw new Exception("Image directory not found");
}
ObservableCollection<Items> LibraryItems = new ObservableCollection<Items>();
// Get files
foreach (string fileName in isoFile.GetFileNames())
{
//string filePath = Path.Combine(imageFolder, imageFileName);
string filePath = Path.Combine(imageFolder, fileName);
using (var imageStream = isoFile.OpenFile(filePath, FileMode.Open, FileAccess.Read))
{
var imageSource = PictureDecoder.DecodeJpeg(imageStream);
BitmapImage bi = new BitmapImage();
ListBoxItem item = new ListBoxItem();
bi.SetSource(imageStream);
item.Content = new Image() { Source = bi, MaxHeight = 100, MaxWidth = 100, Margin = new Thickness(0, 0, 0, 20) };
//MainListBox.Items.Add(item);
b = bi;
}
LibraryItems.Add(new Items(b, h));
MainListBox.ItemsSource = LibraryItems;
}
}
Can anyone help me retrieving all the text saved in isolated storage. The text in isolated file is in the format of "noteTitle^note^imagePath^noteTitle^note^imagePath^...." and so on.. I am trying to retrieve all the noteTitle only.
Can anyone help me with getting all the noteTitle only?
With Regex:
using (var streamReader = new StreamReader(new IsolatedStorageFileStream("ViewFolder\\myFile.txt", FileMode.Open, myStore)))
{
var text = streamReader.ReadToEnd();
var titles = Regex.Matches(text, #"(?<title>[^\^]+)\^(?<note>[^\^]+)\^(?<imagePath>[^\^]+)")
.Cast<Match>()
.Select(arg => arg.Groups["title"])
.ToList();
}
or with Split
using (var streamReader = new StreamReader(new IsolatedStorageFileStream("ViewFolder\\myFile.txt", FileMode.Open, myStore)))
{
var text = streamReader.ReadToEnd();
var i = 0;
var titles = text.Split('^').Where(arg => i++ % 3 == 0).ToList();
}
[EDIT] To bind the list to the ListBox:
private void Library_Loaded(object sender, RoutedEventArgs e)
{
using (var streamReader = new StreamReader(new IsolatedStorageFileStream("ViewFolder\\myFile.txt", FileMode.Open, myStore)))
{
var text = streamReader.ReadToEnd();
var i = 0;
MainListBox.ItemsSource = text.Split('^').Where(arg => i++ % 3 == 0).ToList();
}
}
[EDIT]
Replace this piece of code:
String fileText = readFile.ReadLine();
//noteSeparated is the variable that save the retrieve note from myFile.txt and is noteSeparated by '^'
noteSeparated = fileText.Split(new char[] { '^' });
for (i = 0; i < noteSeparated.Length; i = i + 3)
{
noteSeparate = noteSeparated[i];
a = noteSeparate;
break;
}
h = a;
with:
var fileText = readFile.ReadToEnd();
var i = 0;
var titles = fileText .Split('^').Where(arg => i++ % 3 == 0).ToList();
titles will be a list of the notTitle.