I need an overview of two floors as a treeview. I have a csv, but don't know how to get it into the treeview. I saw many examples but nothing works. Thanks.
That's how my csv looks like:
floor;room;place;pcnumb
4;1;1;6001
4;1;2;6002
4;1;3;6003
4;1;4;6004
...
5;8;82;5082
5;8;83;5027
5;8;84;5084
5;9;85;5028
var reader = new StreamReader(File.OpenRead(#"csvh.csv"));
List<string> listA = new List<string>();
List<string> listB = new List<string>();
while (!reader.EndOfStream)
{
var line = reader.ReadLine();
var values = line.Split(';');
listA.Add(values[0]);
listB.Add(values[1]);
foreach (var column1 in listA)
{
Console.WriteLine(column1);
}
foreach (var column2 in listA)
{
Console.WriteLine(column2);
}
}
That's what I tried, but it doesn't work with my csv
Related
I have 5 datasets coming from Database and have saved them in List like below:
var list1 = new List<Class1>
var list2 = new List<Class2>
var list3 = new List<Class3>
var list4 = new List<Class4>
var list5 = new List<Class5>
I need to convert all 5 lists into a csv file (excel type).
I can do this only for lis1 dataset as of now.
How can we merge all list and print the data in CSV?
The format of the csv file is as follows
Year,Make,Model,Length
1997,Ford,E350,2.35
2000,Mercury,Cougar,2.38
The following code shows how to implement it or you can use ready-made libraries.
public void WriteToCSV()
{
var csv = new StringBuilder();
foreach (var item in list1)
{
string line = "field1,field2,...";
csv.AppendLine(line);
line = string.Format("{0},{1},...",item.field1,...);
csv.AppendLine(line);
}
//.........................................
//.........................................
foreach (var item in list5)
{
string line = "field1,field2,...";
csv.AppendLine(line);
line = string.Format("{0},{1},...",item.field1,...);
csv.AppendLine(line);
}
string fileName = #"D:\WriteText.csv";
if (File.Exists(fileName))
System.IO.File.AppendAllText(fileName, csv.ToString());
else
System.IO.File.WriteAllText(fileName, csv.ToString());
}
example...
List<array> thisListOfArray = new List<array>();
List<string> thisArrayA= new List<string>();
List<string> gMaintenanceB = new List<string>();
thisArrayA.Add("ItemA1");
thisArrayA.Add("ItemA2");
thisArrayA.Add("ItemA3");
thisArrayB.Add("ItemB1");
thisArrayB.Add("ItemB2");
thisArrayB.Add("ItemB3");
thisListOfArray.Add(thisArrayA.ToArray());
thisListOfArray.Add(thisArrayB.ToArray());
I want to get every value that I have inputted inside the thisListOfArray.
you can get it following way. here is the code
List<string[]> thisListOfArray = new List<string[]>();
List<string> thisArrayA = new List<string>();
List<string> thisArrayB = new List<string>();
thisArrayA.Add("ItemA1");
thisArrayA.Add("ItemA2");
thisArrayA.Add("ItemA3");
thisArrayB.Add("ItemB1");
thisArrayB.Add("ItemB2");
thisArrayB.Add("ItemB3");
thisListOfArray.Add(thisArrayA.ToArray());
thisListOfArray.Add(thisArrayB.ToArray());
List<string> lstNewstring = new List<string>();
foreach (var strArray in thisListOfArray)
{
foreach (var str in strArray)
{
lstNewstring.Add(str);
}
}
MessageBox.Show(lstNewstring.Count.ToString());
Change your code like this:
List<List<string>> thisListOfArray = new List<List<string>>();
List<string> thisArrayA = new List<string>();
List<string> gMaintenanceB = new List<string>();
thisArrayA.Add("ItemA1");
thisArrayA.Add("ItemA2");
thisArrayA.Add("ItemA3");
gMaintenanceB.Add("ItemB1");
gMaintenanceB.Add("ItemB2");
gMaintenanceB.Add("ItemB3");
thisListOfArray.Add(thisArrayA);
thisListOfArray.Add(gMaintenanceB);
foreach (var itm in thisListOfArray.SelectMany(item => item))
{
MessageBox.Show(itm);
}
If you have:
List<string[]> listOfArray
string[] array
Add the array to the List with listOfArray.Add(array);
Not sure where you'll be getting array from.
Try to put some data from List to dataGridView, but have some problem with it.
Currently have method, that return me required List - please see picture below
code
public List<string[]> ReadFromFileBooks()
{
List<string> myIdCollection = new List<string>();
List<string[]> resultColl = new List<string[]>();
if (chooise == "all")
{
if (File.Exists(filePath))
{
using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read))
{
StreamReader sr = new StreamReader(fs);
string[] line = sr.ReadToEnd().Split(new string[] { Environment.NewLine },
StringSplitOptions.RemoveEmptyEntries);
foreach (string l in line)
{
string[] result = l.Split(',');
foreach (string element in result)
{
myIdCollection.Add(element);
}
resultColl.Add(new string[] { myIdCollection[0], myIdCollection[1], myIdCollection[2], myIdCollection[3] });
myIdCollection.Clear();
}
sr.Close();
return resultColl;
}
}
....
this return to me required data in requred form (like list from arrays).
After this, try to move it to the dataGridView, that already have 4 columns with names (because i'm sure, that no than 4 colums required) - please see pic below
Try to put data in to dataGridView using next code
private void radioButtonViewAll_CheckedChanged(object sender, EventArgs e)
{
TxtLibrary myList = new TxtLibrary(filePathBooks);
myList.chooise = "all";
//myList.ReadFromFileBooks();
DataTable table = new DataTable();
foreach (var array in myList.ReadFromFileBooks())
{
table.Rows.Add(array);
}
dataGridViewLibrary.DataSource = table;
}
But as result got error - "required more rows that exist in dataGridVIew", but accordint to what I'm see (pic above) q-ty of rows (4) equal q-ty of arrays element in List (4).
Try to check result by putting additional temp variables - but it's ok - please see pic below
Where I'm wrong? Maybe i use dataGridView not in correct way?
EDIT
example of file (simple csv)
11111, Author, Name, Categories
11341, Author1, Name1, Categories1
You need to add columns to your DataTable first before adding rows:
private void radioButtonViewAll_CheckedChanged(object sender, EventArgs e)
{
TxtLibrary myList = new TxtLibrary(filePathBooks);
myList.chooise = "all";
DataTable table = new DataTable();
//add columns first
table.Columns.Add("ID");
table.Columns.Add("Author");
table.Columns.Add("Caption");
table.Columns.Add("Categories");
//then add rows
foreach (var array in myList.ReadFromFileBooks()) {
table.Rows.Add(array);
}
dataGridViewLibrary.DataSource = table;
}
I think your code it's too complex. SImply, if you want see all data in the table from the file, you can do this
if (!System.IO.File.Exists("file.txt"))
return;
dgvDataGridView.ColumnCount = 4;
dgvDataGridView.Columns[0].HeaderCell.Value = "ID";
dgvDataGridView.Columns[1].HeaderCell.Value = "Author";
dgvDataGridView.Columns[2].HeaderCell.Value = "Caption";
dgvDataGridView.Columns[3].HeaderCell.Value = "Categories";
using (System.IO.StreamReader sr = new System.IO.StreamReader("file.txt"))
while (sr.Peek() > -1)
dgvDataGridView.Rows.Add(sr.ReadLine().Split(','));
Using LINQ, how I can retrieve list of list of item where match with another list?
Example:
List<string> data = new List<string>();
List<List<string>> datas = new List<List<string>>();
List<string> dataSearch = new List<string>();
dataSearch.Add("01");
dataSearch.Add("02");
data.Add("01");
data.Add("Book");
data.Add("9");
datas.Add(data);
data = new List<string>();
data.Add("02");
data.Add("Pen");
data.Add("2");
datas.Add(data);
data = new List<string>();
data.Add("03");
data.Add("Pencil");
data.Add("5");
datas.Add(data);
Expected Result in List<List<string>>:
List<string> ("01", "Book", "9")
List<string> ("02", "Pen", "2")
I try
var result = datas.Where(x => x[0].Contains(dataSearch)).ToList();
I got red underline in editor.
This is what you are looking for:
List<string> data = new List<string>();
List<List<string>> datas = new List<List<string>>();
List<string> dataSearch = new List<string>();
dataSearch.Add("01");
dataSearch.Add("02");
// same as your code
var result = datas.Where(i => dataSearch.Contains(i[0])).ToList();
If the three items in the List<List<string>> has a closely bound relationship it is better to create a class for this and then make a list of these objects.
Class StationaryItem
{
int ItemCode;
String ItemName;
float Price;
public StationaryItem(int Code, string ItemName,float Price)
{
this.ItemCode = Code;
this.ItemName = ItemName;
this.Price = Price;
}
}
public static void Main ()
{
List<StationaryItem> ItemList = new List<StationaryItems>
ItemList.Add( new StationaryItem(01,"Pen",20));
ItemList.Add( new StationaryItem(02,"Pencil",5));
//After you make a class like this you can use Linq to manuplate easily
}
I have an log file like this..
This is the segment 1
============================
<MAINELEMENT><ELEMENT1>10-10-2013 10:10:22.444</ELEMENT1><ELEMENT2>1111</ELEMENT2>
<ELEMENT3>Message 1</ELEMENT3></MAINELEMENT>
<MAINELEMENT><ELEMENT1>10-10-2013 10:10:22.555</ELEMENT1><ELEMENT2>1111</ELEMENT2>
<ELEMENT3>Message 2</ELEMENT3></MAINELEMENT>
This is the segment 2
============================
<MAINELEMENT><ELEMENT1>10-11-2012 10:10:22.444</ELEMENT1><ELEMENT2>2222</ELEMENT2>
<ELEMENT3>Message 1</ELEMENT3></MAINELEMENT>
<MAINELEMENT><ELEMENT1>10-11-2012 10:10:22.555</ELEMENT1><ELEMENT2>2222</ELEMENT2>
<ELEMENT3>Message 2</ELEMENT3></MAINELEMENT>
How can I read this into DataTable excluding the data This is the segment 1 and This is the segment 2 and ====== lines completely.
I would like to have the Datatable as with Columns as "ELEMENT1", "ELEMENT2", "ELEMENT3" and fill the details with the content between those tags in the order of print of line.
It should not change the sequence of the order of records in the table while inserting.
HtmlAgilityPack seems to be a good tool for what you need:
using HtmlAgilityPack;
class Program
{
static void Main(string[] args)
{
var doc = new HtmlDocument();
doc.Load("log.txt");
var dt = new DataTable();
bool hasColumns = false;
foreach (HtmlNode row in doc
.DocumentNode
.SelectNodes("//mainelement"))
{
if (!hasColumns)
{
hasColumns = true;
foreach (var column in row.ChildNodes
.Where(node => node.GetType() == typeof(HtmlNode)))
{
dt.Columns.Add(column.Name);
}
}
dt.Rows.Add(row.ChildNodes
.Where(node => node.GetType() == typeof(HtmlNode))
.Select(node => node.InnerText).ToArray());
}
}
}
could do this, where stringData is the data from the file you have
var array = stringData.Split(new[] { "============================" }, StringSplitOptions.RemoveEmptyEntries);
var document = new XDocument(new XElement("Root"));
foreach (var item in array)
{
if(!item.Contains("<"))
continue;
var subDocument = XDocument.Parse("<Root>" + item.Substring(0, item.LastIndexOf('>') + 1) + "</Root>");
foreach (var element in subDocument.Root.Descendants("MAINELEMENT"))
{
document.Root.Add(element);
}
}
var table = new DataTable();
table.Columns.Add("ELEMENT1");
table.Columns.Add("ELEMENT2");
table.Columns.Add("ELEMENT3");
var rows =
document.Descendants("MAINELEMENT").Select(el =>
{
var row = table.NewRow();
row["ELEMENT1"] = el.Element("ELEMENT1").Value;
row["ELEMENT2"] = el.Element("ELEMENT2").Value;
row["ELEMENT3"] = el.Element("ELEMENT3").Value;
return row;
});
foreach (var row in rows)
{
table.Rows.Add(row);
}
foreach (DataRow dataRow in table.Rows)
{
Console.WriteLine("{0},{1},{2}", dataRow["ELEMENT1"], dataRow["ELEMENT2"], dataRow["ELEMENT3"]);
}
I'm not so sure where you problem is.
You can use XElement for reading the xml and manually creating DataTable.
For Reading the XML See Xml Parsing using XElement
Then you can create dynamically the datatable.
Heres an example of creating a datatable in code
https://sites.google.com/site/bhargavaclub/datatablec
But why do you want to use a DataTable ? There are a lot of downsides...