Hi all,
Need help, How can i read a dat file in c# and display data in datagridview.
the data is in a comma format. Ie
a,b,c,d etc.......
many thanks,
Hi all,
Need help, How can i read a dat file in c# and display data in datagridview.
the data is in a comma format. Ie
a,b,c,d etc.......
many thanks,
So it's actually a CSV file.
Try this:
private void PopulateDataGridView()
{
string filePath = "<path to dat file>";
System.IO.TextReader reader = new System.IO.StreamReader(filePath);
bool colAdded = false;
DataTable table = new DataTable("data");
try
{
while (reader.Peek() != -1)
{
string[] tokens = System.Text.RegularExpressions.Regex.Split(reader.ReadLine(), ",");
if (!colAdded)
{
foreach (string token in tokens)
{
table.Columns.Add(token);
}
colAdded = true;
}
else
{
DataRow row = table.NewRow();
for (int i = 0; i < table.Columns.Count; i++)
{
row[i] = tokens[i];
}
table.Rows.Add(row);
}
}
dataGridView1.DataMember = "data";
dataGridView1.DataSource = table;
}
finally
{
if (reader != null)
reader.Close();
}
}
Hi All,
I tried this code. But I got error message in the code "table.Columns.Add(token);".
message is "A column named '1' already belongs to this DataTable."
please help me to fix this.
private void PopulateDataGridView()
{
string filePath = "<path to dat file>";
System.IO.TextReader reader = new System.IO.StreamReader(filePath);
bool colAdded = false;
DataTable table = new DataTable("data");
try
{
while (reader.Peek() != -1)
{
string[] tokens = System.Text.RegularExpressions.Regex.Split(reader.ReadLine(), ",");
if (!colAdded)
{
foreach (string token in tokens)
{
table.Columns.Add(token);
}
colAdded = true;
}
else
{
DataRow row = table.NewRow();
for (int i = 0; i < table.Columns.Count; i++)
{
row[i] = tokens[i];
}
table.Rows.Add(row);
}
}
dataGridView1.DataMember = "data";
dataGridView1.DataSource = table;
}
finally
{
if (reader != null)
reader.Close();
}
}
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.