ahern8
ahern8

Reputation: 13

Displaying specific number of records from text file

Im having an issue loading just 3 records from the text file into a datagridview.

private void button1_Click(object sender, EventArgs e)
       {
           using (OpenFileDialog ofd = new OpenFileDialog())
           {
               if (ofd.ShowDialog() == DialogResult.OK && radioButton1.Checked)
               {
                   System.IO.StreamReader file = new System.IO.StreamReader(ofd.FileName);
                   string[] columnnames = file.ReadLine().Split('|');
                   List<string> list = new List<string>();
                   DataTable dt = new DataTable();
                   foreach (string c in columnnames)
                   {
                       dt.Columns.Add(c);
                   }
                   string newline;
                   while ((newline = file.ReadLine()) != null)
                   {
                       DataRow dr = dt.NewRow();
                       string[] values = newline.Split('|');
                       for (int i = 0; i < values.Length; i++)
                       {
                           dr[i] = values[i];

                       }

                       dt.Rows.Add(dr);

                   }
                   file.Close();
                   dataGridView1.DataSource = dt;
               }

           }

Im trying to have someone select a radio button such as "show 3 records" and open a text file. Then it would list the 3 records only in a datagridview. I can get the file to load the file but can't figure out how to make it only show 3 records from the text file. Could someone help me please?

Upvotes: 1

Views: 101

Answers (2)

TheGeneral
TheGeneral

Reputation: 81493

Use File.ReadLines and Take

var records = File.ReadLines(ofd.FileName).Take(3);

foreach(var record in records)
{
    // do stuff
}

The advantages of this approach, is under the hood ReadLines creates an iterator and calls the plumbing for StreamReader and reads each line individually. When combined with Take it only reads and loads what is iterated( in this case the first 3 lines).

You can find (and follow) the source code here

https://referencesource.microsoft.com/mscorlib/R/d989485a49fbbfd2.html


Additional Resources

File.ReadLines Method

Reads the lines of a file.

Enumerable.Take(IEnumerable, Int32) Method

Returns a specified number of contiguous elements from the start of a sequence.

Upvotes: 4

Richard Schneider
Richard Schneider

Reputation: 35477

You need to count the number lines of read and then exit the read-load when it reaches 3 lines.

int maxLines = 3;
string newline;
while ((newline = file.ReadLine()) != null && --maxLines >= 0)
{
   ....
}

Upvotes: 1

Related Questions