You must Sign In to post a response.
  • Category: Visual Studio

    Import Data from .dat files to DataGridView in VB.net

    Hi Everyone

    I want to import data to DataGridView from .dat file.

    The file is generated by Time Attendance Machine.

    It has records as follows

    NOTE :

    THERE IS NO COLUMN HEADER
    THERE IS A SPACE BEFORE THE RECORD STARTS


    15 2016-10-31 07:22:24 1 0 1 0
    8 2016-10-31 07:29:57 1 0 1 0
    10 2016-10-31 07:46:06 1 0 1 0
    14 2016-10-31 08:09:34 1 0 1 0
    4 2016-10-31 08:17:53 1 0 1 0
    1 2016-10-31 08:18:21 1 0 1 0
    3 2016-10-31 08:32:36 1 0 1 0
    13 2016-10-31 08:34:53 1 0 1 0
    11 2016-10-31 08:44:42 1 0 1 0
    8 2016-10-31 16:38:08 1 0 1 0
    10 2016-10-31 17:23:02 1 0 1 0
    15 2016-10-31 17:23:48 1 0 1 0
    3 2016-10-31 17:23:51 1 0 1 0
    4 2016-10-31 17:30:41 1 0 1 0
    14 2016-10-31 17:32:03 1 0 1 0
    11 2016-10-31 17:33:40 1 0 1 0
    13 2016-10-31 17:33:51 1 0 1 0
    1 2016-10-31 17:33:54 1 0 1 0

    Thanks in advance
  • #769636
    Hi Dinesh,

    You can read file using StreamReader and store values in DataTable than bind the data table to gridview.

    Refer the below link for reading data from file to data table:
    https://stackoverflow.com/questions/20860101/how-to-read-text-file-to-datatable

    Hope this will help you.

    Regards,
    Nirav Lalan
    DNS Gold Member
    "If you can dream it, you can do it."

  • #769690
    you can try with below logic

    private void LoadDataGridView()
    {
    string filePath = ""c://sample1.dat";
    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();
    }
    }

    Hope, this will directly useful to get the data from .dat file and then bind to datatgrid viewl

    Thanks!
    B.Ramana Reddy


  • Sign In to post your comments