C# - csv to form text-fields (copy and paste) - c#

I have form:
and a csv file containing these values:
110977,3871933,317731,0,
How would I be able to copy the CSV data and paste it into all the correct fields in one copy and paste action? (All the data will be in the correct order)
Thanks in advance!

I would suggest reading the CSV file by opening it, then split by comma, put your values into the string array and then update your textBoxes.
Refer to the answer to this question.
You can also use OpenFileDialog to provide the UI for opening the file.
EDIT:
I prepared some basic example to handle exactly the case you asked for. It assumes you have 4 values in the copied CSV line separated by comma (anyway if you have more than 4 in copied line just first 4 will be put into textBoxes). It only requires to copy the CSV line and paste it using Ctrl + V into the first textBox (txtValue1) so it is then splitted by , and all those values from copied CSV line are put into corresponding textBoxes (txtValue1, txtValue2, txtValue3, txtValue4 consecutively).
My form looks just like that:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
txtValue1.KeyDown += TxtValue1_KeyDown;
}
private void TxtValue1_KeyDown(object sender, KeyEventArgs e)
{
if (e.Control && e.KeyCode == Keys.V)
{
string csvLine = Clipboard.GetText();
if (String.IsNullOrEmpty(csvLine))
return;
string[] values = csvLine.Split(',');
if (values.Count() < 4)
return;
txtValue1.Text = values[0];
txtValue2.Text = values[1];
txtValue3.Text = values[2];
txtValue4.Text = values[3];
e.SuppressKeyPress = true;
}
}
}
It could of course be made more generic and handle possible exceptions. This is only to show how to solve what you need easily.

Copy/Pasting? More like reading CSV from a stream ?
Create a Model aka a class to store the values once you start reading the CSV using any sort of stream reader. As you read the positions of the fields from the CSV you can start storing them into your model and then it is easy from there. You might want to think about reading everything into a List, so you only read once.
Here is your class
public class Model
{
public string InvoiceNumber { get; set; }
...
}
Here is the CSV reading piece
using (StreamReader sr = new StreamReader(sourceFileName))
{
List<Model> modelList = new List<Model>();
string headerLine = sr.ReadLine();
string currentLine;
for (int i = 0; i < strArray.Length; i++)
{
while ((currentLine = sr.ReadLine()) != null)
{
string[] strArray = currentLine.Split(',');
Model myModel = new Model();
switch (i)
{
case 0: myModel.InvoiceNumber = = strArray[i]; break;
case 1: myModel.InvoiceHeaderId = strArray[i]; break;
}
}
}
modelList.Add(myModel);
}
}
From Here you can assign this to the UI.It depends which row you want to read, maybe filter the result to get the id, or filter my other pieces of data. Up to you to decide, you can add those filters in the for each loop. Or even better, take a look at LINQ. :D
foreach (var item in modelList)
{
txtInvoiceNumber.Text = mymodel.InvoiceNumber;
txtinvoiceHeaderId.Text = mymodel.InvoiceHeaderId;
}

Related

C#: Read line from file & determine if it contains a substring

I am working on a program for personal use that will automatically sort a grocery list (from file) into a particular order. I want the program to open the file, read each line, and determine if each line contains certain words. For example, a line could contain "chicken breasts," and the program would just recognize that it contained "chicken." The idea is to have the program automatically order my list so that I'm not running back and forth getting items when I go to the store. Currently the external file line must have the exact text "chicken" for the program to recognize it ("chicken breasts" will not be recognized). Here is the section that I believe is giving me trouble:
if (groceries.Contains("chicken"))
{
chicken = "Chicken";
lstItems.Items.Add(chicken);
}
Groceries is an array with each element being a line from the file (I think I created it correctly). Below is the entire code:
private void btnImport_Click(object sender, EventArgs e)
{
//Grocery items
string chicken;
//StreamReader variable
StreamReader readFile;
string filePath;
//Counter variable
int index = 0;
//Display open file dialog box
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.ShowDialog();
if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
//Set filepath as a variable
filePath = openFileDialog1.FileName;
// Assign the file as a variable
readFile = File.OpenText(filePath);
//Count lines in file and create array
int lineCount = File.ReadLines(filePath).Count();
string[] groceries = new string[lineCount];
//Read file's contents
while (index < groceries.Length && !readFile.EndOfStream)
{
groceries[index] = readFile.ReadLine();
index++;
if (groceries.Contains("chicken"))
{
chicken = "Chicken";
//Display items in label
lstItems.Items.Add(chicken);
}
}
//Close file
readFile.Close();
}
}
When the program is run, it will add "Chicken" to the listbox the same number of times as the number of lines in the file, even though only one line actually contains "chicken." My question is: How can I make it pick out the keyword from a longer line of text, and why is it adding the item more than once? Thanks!
Edit
(Sorry I don't know how to attach a file here)
I am currently importing a .txt file with the following data:
chicken
fish
Frosted Flakes cereal
pork tenderloin
ground beef
First, you need to remove the redundant openFileDialog1.ShowDialog();. And access the elements in groceries by index. Then add additional conditions to exclude rows that contain "chicken breasts". Note that index++ is executed after the if statement.
// define a varibale
bool chickenadded = false;
OpenFileDialog openFileDialog1 = new OpenFileDialog();
// remove the redundant ShowDialog
if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
// code omitted ...
//Read file's contents
while (index < groceries.Length && !readFile.EndOfStream)
{
groceries[index] = readFile.ReadLine();
// check here
if (groceries[index].Contains("chicken") && !chickenadded /*&& !groceries[index].Contains("chicken breasts")*/)
{
chicken = "Chicken";
lstItems.Items.Add(chicken);
// set to true
chickenadded = true;
// another way is not define boolean, just use "break"
break;
}
// reset index here
index++;
}
Disregarding any other problem or what the overall goal of the application is. You forgot to look at the actual line
if (groceries[index].Contains("chicken"))
It's worth a note that you should likely be using File.ReadLines or File.ReadAllLines instead. As it gives you a collection or enumerable to work with

How can I put listbox text/items into a text file?

So I want to make some sort of management system or list maker. And I want the data to be stored in a text file. Here's what I have.
So when you click then exit button on the form
private void btnExit_Click(object sender, EventArgs e)
{
if (!File.Exists("paste.txt"))
{
}
else if (File.Exists("paste.txt"))
{
File.Delete("paste.txt");
StreamWriter file = new StreamWriter("paste.txt");
string text = listBox1.Text;
file.Write(text);
file.Close();
}
this.Close();
}
So I want it to save all the text in the textbox to a text file. How could I do this? Right now when I click the exit button the file stays blank.
You can use File.WriteAllText. This will overwrite what's in it at all times, so there's no point in deleting it first if that's what you want.
var path = "paste.txt";
var listBoxText = "";
foreach(var item in listBox1.Items)
{
listBoxText += item.ToString() + "\n";
}
if (File.Exists(path))
{
File.WriteAllText(path, listBoxText, Encoding.UTF8);
}
Not sure what your requirements are OP, but if you also want to create the File if doesn't exist, you could do:
var file = new FileInfo(path);
file.Directory.Create(); // will do nothing if it already exists
File.WriteAllText(path, listBox1.Text, Encoding.UTF8);
https://learn.microsoft.com/en-us/dotnet/api/system.io.file.writealltext?view=netframework-4.8
Here is the pretty way of doing it
Lets say you have an item object
public class ListItem
{
public string Value { get; set; }
public string Description { get; set; }
public string DisplayValue
{
get
{
return $"[{Value}] - {Description}";
}
}
}
You see, I provided an object that could be like that, more complex object, but could be just a string.
When you add objects you create a list and do something like this
var itemList = new List<ListItem>();
// add items
myLst.DisplayMember = "DisplayValue";
myLst.ValueMember = "Value";
myLst.DataSourse = itemList;
In this case you can get the list of "any property" like this (System.Linq)
string[] fileLines =
((List<ListItem>)myLst.DataSourse).Select(itm => itm.Value).ToArray();
Or, if your items are simple strings
string[] fileLines = (from itm in myLst.Items select itm).ToArray();
And then use your file logic to simply in the end call
File.WriteAllLines(path, fileLines);
What I like about this approach is that no explicit loops needs and item can be a more complex item that can have a bunch of properties beyond a simple string description/value in one.

AutoComplete textBox from a certain position of each line of a .txt file

I have a textBox named "textBoxCliente" and I want it to appear suggestions when I writte in there from the .txt file.
The suggestions that I want to appear from the .txt file are in the position 1 "parts[1]", each position are separated with the caracter "|".
My .txt file is this:
1|Rui|Lisboa|rui#hotmail.com|912345324|14/01/2000|89564352|Empresa
2|Henrique|Evora|henrique#hotmail.com|914445324|17/05/2001|55464352|Particular
3|Andre|Agueda|andre#hotmail.com|932415374|12/11/1996|23456743|Particular
4|Pedro|Aveiro|pedro#hotmail.com|965342163|30/03/2002|98645372|Empresa
My code is:
public partial class Vender : UserControl
{
public Vender()
{
InitializeComponent();
}
string dir = (Environment.CurrentDirectory + "/Bd/clientes.txt");
string[] sug = new string[File.ReadAllLines(Environment.CurrentDirectory +
"/Bd/clientes.txt").Count()];
private void textBoxCliente_TextChanged(object sender, EventArgs e)
{
carrSug();
for (int i = 0; i < sug.Length; i++)
{
textBoxCliente.AutoCompleteCustomSource.Add(sug[i]);
}
textBoxCliente.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
}
private void carrSug()
{
string[] lines = File.ReadLines(dir).ToArray();
int nLine = File.ReadAllLines(dir).Count();
for (int j = 0; j <= nLine - 1; j++)
{
string[] parts = lines[j].Split(new char[] { '|' });
sug[j] = parts[1];
}
}
}
What I did was using the "string[] sug" to save the values of the position 1 of each line and then use it to show the suggestions.
As a programmer, get better at reading carefully. Here is the documentation for AutoCompleteCustomSource:
Gets or sets a custom System.Collections.Specialized.StringCollection to use when the System.Windows.Forms.TextBox.AutoCompleteSource property is set to CustomSource.
Emphasis Mine
See the bolded part in the above, make sure you do that:
textBoxCliente.AutoCompleteSource = AutoCompleteSource.CustomSource;
Also, you do not need to do that every time the user types. The event handler textBoxCliente_TextChanged will be called every time the text changes. Instead, put the code in the constructor or in the form's load event.
Some Suggestions
Give your methods meaningful names. For example, carrSug() is not very meaningful. Plus it does not follow the C# coding conventions--it looks like Java. Also, keep the method cohesive. You are doing some parts of the suggestion in the carrSug() and then some of it you are doing in textBoxCliente_TextChanged. Here is a more meaningful method:
private AutoCompleteStringCollection clientSuggestions;
private void LoadClientSuggestions()
{
this.clientSuggestions = new AutoCompleteStringCollection();
string[] suggestionsFromFile = File.ReadLines("YourPath.txt").Select(x => x.Split('|').Skip(1).First()).ToArray();
this.clientSuggestions.AddRange(suggestionsFromFile);
}
The above method uses Ling so make sure to import: using System.Linq;
Here is how to use it (Put this code in your form's constructor or Load method):
this.LoadSuggestions();
this.textBoxCliente.AutoCompleteSource = AutoCompleteSource.CustomSource;
this.textBoxCliente.AutoCompleteCustomSource = this.clientSuggestions;
this.textBoxCliente.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
Why did I put the word Load in the method name? Because, it returns nothing so Load adds meaning.
Also, stop writing the same string multiple times:
"/Bd/clientes.txt"
Make that a constant so if you need to change it, you change it in one place.

C# Windows Form search txt file for passed data and pass to textboxes

I'm relatively new to C# and have spent an inordinate amount of time trying to figure this out myself with no luck. Hoping you guys can help.
I have 2 windows forms. In the first form, the user enters a citation number. I want to take that citation number, search for it in an external text file, and then return all of the data in the row for that citation into separate textboxes.
The text file looks something like this:
S8729936 , 6JXV123 , 10/1/2015 , 10/31/2015 , PAID , 49.5
A7472601 , 2NXP234 , 10/12/2015 , 11/11/2015 , UNPAID , 99
W2041810 , 5JPB345 , 10/19/2015 , 11/18/2015 , UNPAID , 99
And the second form has 6 textboxes. I have it so that the citation number, let's say S8729936 is passed into the first textbox, but I cannot seem to figure out how to then search the text file for S8729936 and give me the rest of the data in the row inside the textboxes.
Here are some examples of things I've tried. I've been copying and pasting and then messing with code all day, so if the details don't seem to match, that's probably the reason.
public Form2(string citation)
{
InitializeComponent();
txtCitation2.Text = citation;
const string FILENAME = #"\Path\ProjectData.txt";
FileStream fsInFile = new FileStream(FILENAME, FileMode.Open, FileAccess.Read);
StreamReader srReader = new StreamReader(fsInFile);
const char CH_DELIM = ',';
string strRecordIn;
string[] strFields;
if (strFields != null)
{
strRecordIn = srReader.ReadLine();
strFields = strRecordIn.Split(CH_DELIM);
txtLicense2.Text = strFields[1];
}
strRecordIn = srReader.ReadLine();
srReader.Close();
fsInFile.Close();
}
No luck there, how about something along the lines of this:
string whole_file = File.ReadAllText(#"Path\ProjectData.txt");
whole_file = whole_file.Replace('\n', '\r');
string[] lines = whole_file.Split(new char[] { '\r' });
int num_rows = lines.Length;
int num_cols = lines[0].Split(',').Length;
string[,] values = new string[num_rows, num_cols];
for (int r = 0; r < num_rows; r++)
{
string[] line_r = lines[r].Split(',');
for (int c = 0; c < num_cols; c++)
{
values[r, c] = line_r[c];
}
}
txtLicense2.Text = lines[1];
Nope. Maybe something along the lines of this:
const string FILENAME = #"C:\Users\rfranklin\Documents\ProjectData.txt";
FileStream fsinfile = new FileStream(FILENAME, FileMode.Open, FileAccess.Read);
StreamReader srReader = new StreamReader(fsinfile);
const string CH_DELIM = " ,";
string strRecordIn;
string[] strFields = new string[10];
string citnum = citation;
bool found = false;
strRecordIn = srReader.ReadLine();
foreach(string x in strFields)
{
if (x == citation)
{
found = true;
break;
}
}
if (found)
{
txtLicense2.Text = strFields[1];
}
Still no luck. And on and on. It seems as though I'm mostly missing how to tell the program what to search for and I am not sure what else to do. Like I said, I've been Googling various ways to do it all day, but I can't seem to make anything work right.
I'm doing this in Visual Studio 2013, if that helps.
Any help would be immensely appreciated. Thanks.
If the number of lines in the CSV file is not too large (I wouldn't know what "too large" is), then you could leverage a few .NET constructs, such as Data Binding and Linq to achieve this.
For starters, I would create a class that implements INotifyPropertyChanged:
namespace Citations
{
public class Citation : INotifyPropertyChanged
{
public static Citation ParseLine(string line)
{
Citation cit = new Citation();
if (string.IsNullOrEmpty(line))
throw new ArgumentException("Invalid argument", nameof(line));
string[] vals = line.Split(',');
if (vals.Length != 6)
throw new ArgumentOutOfRangeException(nameof(line), "Invalid format");
cit.CitationNumber = vals[0].Trim();
cit.PlateNumber = vals[1].Trim();
cit.DateCreated = DateTime.Parse(vals[2].Trim());
cit.DateExpired = DateTime.Parse(vals[3].Trim());
cit.Status = vals[4].Trim();
cit.Amount = Decimal.Parse(vals[5].Trim());
return cit;
}
void RaisePropertyChanged(string prop)
{
if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(prop)); }
}
public event PropertyChangedEventHandler PropertyChanged;
string citationNumber;
public string CitationNumber
{
get
{
return citationNumber;
}
set
{
if (citationNumber != value)
{
citationNumber = value;
RaisePropertyChanged(nameof(CitationNumber));
}
}
}
string plateNumber;
public string PlateNumber
{
get
{
return plateNumber;
}
set
{
if (plateNumber != value)
{
plateNumber = value;
RaisePropertyChanged(nameof(PlateNumber));
}
}
}
DateTime dateCreated;
public DateTime DateCreated
{
get
{
return dateCreated;
}
set
{
if (dateCreated != value)
{
dateCreated = value;
RaisePropertyChanged(nameof(DateCreated));
}
}
}
DateTime dateExpired;
public DateTime DateExpired
{
get
{
return dateExpired;
}
set
{
if (dateExpired != value)
{
dateExpired = value;
RaisePropertyChanged(nameof(DateExpired));
}
}
}
string status;
public string Status
{
get
{
return status;
}
set
{
if (status != value)
{
status = value;
RaisePropertyChanged(nameof(Status));
}
}
}
Decimal amount;
public Decimal Amount
{
get
{
return amount;
}
set
{
if (amount != value)
{
amount = value;
RaisePropertyChanged(nameof(Amount));
}
}
}
}
}
This class is responsible for splitting a line from the CSV file, and converting it to an object of type Citation, which will be used to data bind the textboxes in Form2 later on.
Then in the first Form, I would simply read the file, and using some Linq operators, convert the file to a Dictionary of Citation objects, the key of the Dictionary being the Citation number:
private void button1_Click(object sender, EventArgs e)
{
string[] allLines = File.ReadAllLines("Citations.csv");
Dictionary<string, Citation> dict = allLines.Select(l => Citation.ParseLine(l)).ToDictionary(c => c.CitationNumber, k => k);
Citation cit = dict["W2041810"];
Form2 frm2 = new Form2();
frm2.SetCitation(cit);
frm2.ShowDialog();
}
In the code above, we're using the ToDictionary Linq operator to create a Disctionary from your Citation objects, and the Dictionat key is the Citation number.
Here I'm hardcoding one of the citations for lookup and passing to Form2, which would have a SetCitation method like this:
public void SetCitation(Citation citation)
{
this.citationBindingSource.DataSource = citation;
}
The code to Form2 is a bit difficult to show because I have used the Form designer to setup the data binding for each TextBox, and if I wanted to show that, I'd basically have to show the whole Form2.Designer.cs file.
Instead, I propose to guide you through the process of creating a Project DataSource, then drag & drop the TextBoxes onto Form2 from the Data Sources dialog in Visual Studio.
So, after adding the Citation class to your solution, make sure to compile at leat once so that the "Add data source" wizard will pick that class up as a possible data source.
Then, make sure the Data Sources dialog is displayed by going to View > Other Windows > Data Sources (assuming Visual Studio 2015 here).
From the Data Sources dialog, click the "Add New Data Source button" tolaunch the Data SOurce Configuration Wizard. From the list of possible data sources, you will choose "Object":
Then click the Next button. From the next Wizard step, you will select the Citation class:
and then click the Finish button.
In the Data Sources dialog, you should now have something like this:
From this Data Sources dialog, you can now drag & drop the individual fields onto Form2, which should give you something like this:
You will also notice in the Component tray of Form2, a BindingSource object has been added:
Under the hood, Visual Studio will have set all the Data Binding for your Citation object properties to be displayed in the corresponding TextBox.
This is the "glue" that makes it possible to call Form2.SetCitation() with a Citation object, and have all the fields displayed where they should.
I know this is quite a mouthful to chew on, but believe me, once you understand the principles behind this, you will not want to go back to the kind of spagethi code that you started implementing (no offense, we've all been there).
If you would like me to clarify any specific section of my answer, just let me know, and I'll edit accordingly.
Cheers
A simple winForm version:
using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.IO;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
List<string> matchedList = new List<string>();
public Form1(string citation)
{
InitializeComponent();
string filePath = #"C:\Users\rfranklin\Documents\ProjectData.txt";
string[] linesArr = File.ReadAllLines(filePath);
//find matches
foreach(string s in linesArr)
{
if(s.Contains(citation))
{
matchedList.Add(s); //matched
}
}
//output
foreach(string s in matchedList)
{
Console.WriteLine(s); //write to console
//or output to wherever you wish, eg.
//richTextBox.Text += s + "\n";
}
}
}
}
Note that Form1 needs to be called from somewhere else and take in citation argument. To test it standalone, change it to
public Form1()
{
InitializeComponent();
string citation = "S8729936";
The suggestion from #interceptwind did it for me. Inside the //output section of the code he provided, I basically just created a second array from the matched line, with the elements separated by the comma. The code looks like this:
//output
foreach (string s in matchedList)
{
string citationLine = s;
string[] lineData = citationLine.Split(',');
txtLicense2.Text = lineData[1];
txtIssued2.Text = lineData[2];
txtDue2.Text = lineData[3];
txtStatus2.Text = lineData[4];
txtAmount2.Text = lineData[5];
}
This allowed me to put the data in the textboxes I needed. Thank you all for the assistance!

C# in Visual Studio: How to display a list in a DataGridView? Getting weird stuff

Been a while and I've volunteered to teach myself Windows programming at my company. Started writing vbs scripts and suddenly realized how incredibly useful this programming thing is ;-)
Anyway, I'm a total newbie at C# AND Visual Studio, I kind of get how it works, you drag and drop interface pieces in the design side then wire them together in the back/program side.
I'm trying to write a program that will (ultimately) read in a (very specific kind of) csv file and give the user a friendlier way to edit and sort through it than Excel. Should be simple stuff, and I'm excited about it.
I started this morning and, with the help of the internet, got as far as reading in and parsing the CSV (which is actually a TSV, since they use tabs not commas but hey).
I've been trying to figure out the best way to display the information, and, for now at least, I'm using a DataGridView. But the data isn't displaying. Instead, I'm seeing a long grid of values with column headers of Length, LongLength, Rank, SyncRoot, IsReadOnly, IsFixedSize, and IsSynchronized.
I don't know what any of these mean or where they come from, and unfortunately I don't know how change them either. Maybe somebody can help?
Here is my code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
namespace readInCSV
{
public partial class readInCSV : Form
{
public readInCSV()
{
InitializeComponent();
}
public List<string[]> parseCSV(string path)
{
List<string[]> parsedData = new List<string[]>();
try
{
using (StreamReader readfile = new StreamReader(path))
{
string line;
string[] row;
while ((line = readfile.ReadLine()) != null)
{
row = line.Split('\t');
parsedData.Add(row);
}
}
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
return parsedData;
}
//PRIVATE METHODS FROM HERE ON DOWN
private void btnLoadIn_Click(object sender, EventArgs e)
{
int size = -1;
DialogResult csvResult = openCSVDialog.ShowDialog();
if (csvResult == DialogResult.OK)
{
string file = openCSVDialog.FileName;
try
{
string text = File.ReadAllText(file);
size = text.Length;
}
catch (IOException)
{
}
}
dgView.Dock = DockStyle.Top;
dgView.EditMode = DataGridViewEditMode.EditOnEnter;
dgView.AutoGenerateColumns = true;
dgView.DataSource = parseCSV(openCSVDialog.FileName);
}
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
}
private void openCSVDialog_FileOk(object sender, CancelEventArgs e)
{
}
}
}
Thanks in advance!
What's happening here is that the DataGridView is trying to display all the information for each of the string arrays in your parsedData List.
When you set a DataGridView's DataSource as a List of objects, it attempts to interpret each of the objects as a row to display. parsedData is a List of string array objects, so the grid is showing you all the displayable properties for an array object.
What we can do is parse each TSV row into a custom class (call it TsvRow) which has all the relevant data exposed. The TsvRow objects are then placed in a List and passed to the DataGridView. An example of this approach is explained in this article.
For example:
public class TsvRow
{
// Properties to hold column data
public string Column1 { get; set; }
public string Column2 { get; set; }
}
...
public List<TsvRow> parseCSV(string path)
{
List<TsvRow> parsedData = new List<TsvRow>();
try
{
using (StreamReader readfile = new StreamReader(path))
{
string line;
string[] row;
while ((line = readfile.ReadLine()) != null)
{
row = line.Split('\t');
// Here we assume we know the order of the columns in the TSV
// And we populate the object
TsvRow tsvRow = new TsvRow();
tsvRow.Column1 = row[0];
tsvRow.Column2 = row[1];
parsedData.Add(myObject);
}
}
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
return parsedData;
}
Since all your column data is exposed as properties (i.e. "Column1" and "Column2"), they should be reflected in the DataGridView automatically.
Hope that helps! Please let me know if this needs clarification.
The DataGridView tries to display the Properties of your string-Array. You should set AutoGenerateColumns = false and create the columns by yourself.
Would the first line of the CSV/TSV contain the column names? Is so, you shouldn't pass them as DataSource.
dgView.AutoGenerateColumns = false;
foreach(string name in columnNames)
{
dgView.Columns.Add(name, name);
}

Categories

Resources