C#: Populate Combobox with single column in CSV - c#

I have a csv file with multiple columns, "PROJECT NAME", "PROJECT BUILD". I am trying to populate comobobox with Project Name column only.
Project name column might have multiple repeated names but repeated names should only appear once in combobox as an option to select. For example: in column 1, under "Project Name", Toyota is listed 4 times and Honda is listed 8 Times. Combobox will have 2 things, Toyota and Honda.
Here is my code so far:
// Wehn Form Loads___________________________________________________________________________________________________
public void OnLoad(object sender, RoutedEventArgs e)
{
StreamReader sr = new StreamReader(path);
string column = sr.ReadToEnd();
string[] eachColumn = column.Split(',');
foreach (string s in eachColumn)
{
Project_Name_Combobox.Items.Add(s);
}
}
The current code gets me the entire csv content (row and column) separated by "," listed under combo box. :(. Any help is apricated.

You have to separate out the rows and columns from csv and store whatever you need separately like below.
public void OnLoad(object sender, RoutedEventArgs e)
{
StreamReader sr = new StreamReader(path);
List<string> ProjectNames = new List<string>();
int lineNumber = 1;
while (!sr.EndOfStream)
{
var EachRow = sr.ReadLine();
var Columns= EachRow.Split(',');
if(lineNumber != 1){
ProjectNames.Add(Columns[0]);
}
lineNumber++;
}
ProjectNames = ProjectNames.Distinct().ToList();
foreach(var projectName in ProjectNames){
Project_Name_Combobox.Items.Add(projectName);
}
}

Related

write a comma delimited list to a data grid view

I'm trying to get a csv file into a data table but there are some things in the csv file that I am trying to omit from being entered into the data table, so I wrote it to a list first.
The csv files that i will using the software for have different sections in it for which I then split the whole list into the separate lists for those sections.
After all that was achieved, i needed to skip some lines in each list and wrote the final form i was happy with to lists respective to previous set of lists.
Now I hit a wall, I need to write each of the lists to a respective data grid.
public partial class Form1 : Form
{
String filePath = "";
//list set 1 = list box
List<String> lines = new List<String>();
List<String> accountList = new List<String>();
List<String> statementList = new List<String>();
List<String> summaryList = new List<String>();
List<String> transactionList = new List<String>();
//list set 2 = dgv
List<String> accountList2 = new List<String>();
List<String> statementList2 = new List<String>();
List<String> summaryList2 = new List<String>();
List<String> transactionList2 = new List<String>();
public Form1()
{
InitializeComponent();
}
private void btn_find_Click(object sender, EventArgs e)
{
try
{
using (OpenFileDialog fileDialog = new OpenFileDialog()
{ Filter = "CSV|* .csv", ValidateNames = true, Multiselect = false })
if (fileDialog.ShowDialog() == DialogResult.OK)
{
String fileName = fileDialog.FileName;
filePath = fileName;
}
try
{
if (File.Exists(filePath))
{
lines = File.ReadAllLines(filePath).ToList();
foreach (String line in lines)
{
String addLine = line.Replace("'", "");
String addLine2 = addLine.Replace("\"", "");
String str = line.Substring(0, 1);
int num = int.Parse(str);
if (addLine2.Length > 1)
{
String addLine3 = addLine2.Substring(2);
switch (num)
{
case 2:
accountList.Add(addLine3);
break;
case 3:
statementList.Add(addLine3);
break;
case 4:
summaryList.Add(addLine3);
break;
case 5:
transactionList.Add(addLine3);
break;
}
}
}
}
else
{
MessageBox.Show("Invalid file chosen, choose an appropriate CSV file and try again.");
}
transactionLB.DataSource = transactionList;
//var liness = transactionList;
//foreach (string line in liness.Skip(2))
// transactionList2.Add(line);
//Console.WriteLine(transactionList2);
//var source = new BindingSource();
//source.DataSource = transactionList2;
//trans_dgv.DataSource = source;
accountLB.DataSource = accountList;
summaryLB.DataSource = summaryList;
statementLB.DataSource = statementList;
}
catch (Exception)
{
MessageBox.Show("Cannot load CSV file, Ensure that a valid CSV file is selected and try again.");
}
}
catch (Exception)
{
MessageBox.Show("Cannot open File Explorer, Something is wrong :(");
}
}
}
EDIT 1:
the table has the following columns for the transaction lists (each of the lists have different columns) :
'Number' , 'Date' , 'Description1' , 'Description2' , 'Description3' , 'Amount' , 'Balance' , 'Accrued Charges'
an example of data in the lines of the transaction list:
9, 02 Sep, Petrol Card Purchase, Shell Kempton Park, 968143*7188 30 Aug, -714.45, -10661.88, 5.5
some liness do contain null values.
If I understand correctly, it seems like you're wanting to get the value of the strings in your string list to appear in your DataGridViews. This can be a little tricky because the DataGridView needs to know which property to display and strings only have the Length property (which probably isn't what you're looking for). There are a lot of ways to go about getting the data you want into the DataGridView. For example you could use DataTables and choose which column you want displayed in the DataGridView. If you want to stick with using string lists, I think you could get this to work by modifying your DataSource line to look something like this:
transactionLB.DataSource = transactionList.Select(x => new { Value = x} ).ToList();
I hope this helps! Let me know if I've misunderstood your question. Thanks!

Displaying delimited text to a listview in c#

I have a text file(location stored in destination in program) I want to read the data line by line and write it to the list view. List View has three columns.
TextFile
Hello*How are you*I am
olleh*uoy era woh*ma I
Output in list view
Hello | How are you | I am
olleh| uoy era woh |ma I
File Name:Program.cs
public void read(string destination)
{
StreamReader sw = File.OpenText(destination);
string s = "";
while ((s = sw.ReadLine()) != null)
{
string[] words = s.Split('*');
foreach(string word in words)
{
// i have no idea how to send it to the list view
}
}
sw.Close();
}
File Name: Form1.cs
private void button1_Click(object sender, EventArgs e)
{
ListViewItem lvi = new ListViewItem();
lvi.SubItems.Add();
lvi.SubItems.Add();
listview1.Items.Add(li);
}
Add your words to list
List<string> wordslist=new List<string>();//global declaration
while ((s = sw.ReadLine()) != null)
{
string[] words = s.Split('*');
foreach(string word in words)
{
wordslist.Add(word);
}
}
then loop to fill data in list view
for(int i=0;i<wordslist.Count-2;i+=3)
{
lvi.SubItems.Add(i);
lvi.SubItems.Add(i+1);
lvi.SubItems.Add(i+2);
listview1.Items.Add(li);
}

How to read a text file's data vertically or column wise

How can we read a text file column by column.
Check my new code: I can read the data row-wise using text.split (' ')
But how can be the file read as column wise? Lets assume that a file contains number of rows and columns but I was able to read the data/value horizontally. The code you see that below that's what I could execute!
SEE THE CODE BELOW:-
private void Form1_Load(object sender, EventArgs e)
{
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
string text = "";
text = textBox1.Text;
string[] arr = text.Split(' ');
textBox2.Text = arr[5];
textBox3.Text = arr[8];
}
private void button3_Click(object sender, EventArgs e)
{
string file_name = "c:\\Excel\\count.txt";
string txtline = "";
System.IO.StreamReader objreader;
objreader = new System.IO.StreamReader(file_name);
do
{
txtline = txtline + objreader.ReadLine() + "\r\n";
txtline = txtline + objreader.ReadToEnd() + "";
this.textBox1.Text = "subzihut";
}
while (objreader.Peek() != -1);
textBox1.Text = txtline;
objreader.Close();
}
private void button2_Click(object sender, EventArgs e)
{
textBox4.Text = textBox2.Text + " " + textBox3.Text;
}
}
}
A textfile contains a sequence of characters, delimited by newline characters and probably other characters which are used as delimiters (usually a comma or a semiciolon).
When you read a file you simply read this stream of characters. There are helper functions which read such a file line-by-line (using the newline character as a delimiter).
In plain .Net there are no methods which read column-by-column.
So you should:
read the file line by line
split each line into fields/columns using string.Split() at the separator character(s)
access only the columns of interest
You can simply read the file line by line, splitt the lines and do whatever you want.
var lines = File.ReadLines(#"c:\yourfile.txt");
foreach(var line in lines)
{
var values = line.Split(' ');
}
public string getColumnString(int columnNumber){
string[] lines = System.IO.ReadAllLines(#"C:\inputfile.txt");
string stringTobeDisplayed = string.Empty;
foreach(string line in lines) {
if(columnNumber == -1){ //when column number is sent as -1 then read full line
stringTobeDisplayed += line +"\n"
}
else{ //else read only the column required
string [] words = line.Split();
stringTobeDisplayed += word[columnNumber] +"\n"
}
}
return stringTobeDisplayed;
}
Maybe this will help you:
public static void ReadFile(string path)
{
List<string> Col1 = new List<string>();
List<string> Col2 = new List<string>();
List<string> Col3 = new List<string>();
using (StreamReader sr = new StreamReader(path))
{
while (sr.EndOfStream)
{
string header = sr.ReadLine();
var values = header.Split(' ');
Col1.Add(values[0]);
Col2.Add(values[1]);
Col3.Add(values[2]);
}
}
}
It's true that sometimes you just don't know where to start. Here are some pointers.
You'll have to read the whole file in, probably using something like a StreamReader.
You can parse the first row into column names. Use StreamReader.ReadLine() to get the first line and then do some simple string parsing on it.
You'll want to create some kind of class/object to store and access your data.
Once you have column names, continue to parse the following lines into the proper arrays.
Some here's a rough idea
using(StreamReader sr = new StreamReadeR("C:\\my\\file\\location\\text.csv"))
{
string header = sr.ReadLine();
List<string> HeaderColumns = new List<string>(header.split(" ", StringSplitOptions.RemoveEmptyEntires));
myModelClass.Header = HeaderColumns;
etc...
You might also consider making some kind of dictionary to access columns by header name and index.

Ordering a comboBox by the int value

having a lot of problems ordering my combobox by value any help is greatly appreacitated
private void Form1_Load(object sender, EventArgs e)
{
//text to hold the conbo box, text is grabed from the AS2W14data.csv file from c:\temp\...
String variable;
variable = "";
//filll in the combo box , create a reader
System.IO.StreamReader sr = System.IO.File.OpenText(#"c:\temp\AS2W14data.csv");
//use a while loop to read the entire file line by line, using the current line to populate the comboBox
while (!sr.EndOfStream)
{
variable = sr.ReadLine();
string[] currentLineIndex = variable.Split(',');
//customer ID is indexed at the string array postion 1
//Customer name is indexed at the string array position 0
cboCustomer.Items.Add(currentLineIndex[1].Trim() + " " + currentLineIndex[0].Trim());
}
//close the file to prevent errors...
sr.Close();
}
this is my code so far and i cant seem to find a way to order it.. help
I would suggest ordering them before adding them to the combo. Also here's a little shortcut for reading a text file. First, you want to read lines by streaming them (ReadLines() returns IEnumerable<string>) into a projection (Select()) where you create an anonymous object with two properties - Id and Name. At the end, you order a collection of these anonymous objects by the Id.
var lines = File.ReadLines(#"c:\temp\AS2W14data.csv")
.Select(l => new
{
Id = int.Parse(l.Split(',')[1].Trim()),
Name = l.Split(',')[0].Trim()
}).OrderBy(i => i.Id);
foreach (var l in lines)
cboCustomer.Items.Add(l.Id + " " + l.Name);
try this code hope it will work alternatively you can use Sorted Property of ComboBox
private void Form1_Load(object sender, EventArgs e)
{
//text to hold the conbo box, text is grabed from the AS2W14data.csv file from c:\temp\...
String variable;
variable = "";
ArrayList Indexs = new ArrayList();
//filll in the combo box , create a reader
System.IO.StreamReader sr = System.IO.File.OpenText(#"c:\temp\AS2W14data.csv");
//use a while loop to read the entire file line by line, using the current line to populate the comboBox
while (!sr.EndOfStream)
{
variable = sr.ReadLine();
string[] currentLineIndex = variable.Split(',');
//customer ID is indexed at the string array postion 1
//Customer name is indexed at the string array position 0
Indexs.Add(new AddIndexValues(currentLineIndex[1].Trim() + " " + currentLineIndex[0].Trim());
}
//close the file to prevent errors...
cboCustomer.DataSource = DataBaseBuilds.Indexs;
sr.Close();
}
public class AddIndexValues
{
private int i_index;
public AddIndexValues(int Index)
{
i_index = Index;
}
public int Index
{
get { return i_index; }
}
}

Change CSV file column name

I have a CSV file which contains four columns i.e Name, Surname, Age, Data of Birth
I want to change the column Name to FullName. How can this be done in c# please?
var reader = new StreamReader(File.OpenRead(#"C:\myCSV.csv"));
var line = reader.ReadLine();
var values = line.Split(';');
var title = line.Split(',');
Console.WriteLine(title[0]);
if (title.Contains("Name"))
{
title[0] = "FullName";
}
Now I'm stuck on how should I continue to change the Column name
If you are attempting to create a new file with 3 columns instead of 4 this would be a starting point, however, you should use a csv parser. This is just a demonstration to show you how to combine the two columns.
string[] lines = System.IO.File.ReadAllLines(#"C:\myCSV.csv");
using (System.IO.StreamWriter file = new System.IO.StreamWriter(#"C:\myCSV2.csv"))
{
foreach (string line in lines)
{
if (line==lines[0])
{ //Change Header
file.WriteLine("Fullname,Age,Date of Birth");
}
else
{
string[] values = line.Split(',');
file.WriteLine(string.Format("{0} {1},{2},{3}",
values[0],values[1],values[2],values[3]));
}
}
}

Categories