Skip to content

Instantly share code, notes, and snippets.

@abdulateef
Created July 2, 2017 07:53
Show Gist options
  • Save abdulateef/e0b5ce28dc07eccbf6dd382be2bdd022 to your computer and use it in GitHub Desktop.
Save abdulateef/e0b5ce28dc07eccbf6dd382be2bdd022 to your computer and use it in GitHub Desktop.
how to load a CSV value from a text file with the column head into a datagridview using c#
public static string[,] LoadCsv(string filename)
{
//get the file text
string text = System.IO.File.ReadAllText(filename);
//split into Lines
text = text.Replace("\n", "\r");
string[] lines = text.Split(new char[] { '\r' }, StringSplitOptions.RemoveEmptyEntries);
// to get how many rows and columns
int rows = lines.Length;
int cols = lines[0].Split(',').Length;
// Allocate the data array.
string[,] values = new string[rows, cols];
//load the array
for(int row = 0; row < rows; row++)
{
string[] line = lines[row].Split(',');
for(int col = 0; col < cols; col++)
{
values[row, col] = line[col];
}
}
return values;
}
private void loadTextFileWithColumnHead(string filepath)
{
//get the data
string[,] values = LoadCsv(filepath);
int numRows = values.GetUpperBound(0) + 1;
int numCloumns = values.GetUpperBound(1) + 1;
ispaly the data
dgvValues.Columns.Clear();
for(int c = 0; c < num_cols; c++)
dgvValues.Columns.Add(values[0, c], values[0, c]);
// Add the data.
for(int r = 1; r < num_rows; r++)
{
dgvValues.Rows.Add();
for(int c = 0; c < num_cols; c++)
{
dgvValues.Rows[r - 1].Cells[c].Value = values[r, c];
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment