Click here to Skip to main content
11,929,675 members (55,783 online)
Click here to Skip to main content
Add your own
alternative version


28 bookmarked

Basic File IO and the DataGridView

, 26 Jul 2008 CPOL
Rate this:
Please Sign up or sign in to vote.
Create a versatile line reading application using the .NET StreamReader and the DataGridView.

Sample Image - LineCounter.png


If you have ever wanted to know how quickly you write code, you have probably counted lines. As programs get more involved and work is shared among a team, it is difficult to know how many lines are "owned" by you.

Lines of code may not be the best way to measure performance (I am imagining a classroom full of monkeys striking Enter, Enter, Enter... ). But sometimes, it is satisfying to say, "Look what was done!"

This articles explores basic file IO, how to manually store results in a DataGridView, and basic event handling.

Wiring up the GUI

The GUI has just a few components. A TextBox provides a place where we can enter the file extensions we are interested in counting. A DataGridView provides a place to show results. A CheckBox provides us some options, and a StatusStrip helps us summarize the results to the user.

Use the Anchor property to adjust how each Control "clings" to the walls of the Form. This allows us to resize the window to get a better view if we have long filenames or a large number of results. Anchoring is one of the convenient layout tools built in to the environment.

Sample image

Now, we will wire up the columns in the DataGridView control. The form editor makes this a breeze. Highlight the DataGridView and select the Columns property.

Sample image

We now have a dialog that can be used to generate our columns. Clicking on the Add button opens an additional dialog that can be used to create columns. Choose a name and header text, and the column type of DataGridViewTextBoxColumn. Other interesting column properties include FillWeight, which affects how much priority the column receives during layout.

Sample image

The next step to giving the GUI functionality is to add event handlers. For example, when we click on the Go button, we want the application to find files that match our search criteria, open them, and count lines.

We can use the form editor to add this handler easily. Just double-click on the Go button, and the event handler is added for us, like so:

private void goButton_Click(object sender, EventArgs e)
  // TODO: Count files here...

Also, the function is registered with the event delegate in the designer.cs file. This is what tells the runtime that we want to run the goButton_Click method when the goButton.Click event is fired.

this.goButton.Click += new System.EventHandler(this.goButton_Click);

Because there may be files found by our program that we want to ignore, we will wire up the DataGridView to gather information about selected files only. We can then pick and choose which results we want to tally up for our final line count.

Using the form editor, we set the MultiSelect property to True and the SelectionMode property to FullRowSelect. All that's left is adding an event handler to respond to changes in the selection. Find the SelectionChanged property in the form editor, and double-click to generate the following method:

private void dgvResult_SelectionChanged(object sender, EventArgs e)
  // TODO: Count the selection here.

which is wired up in the designer.cs file like so:

this.dgvResult.SelectionChanged += 
         new System.EventHandler(this.dgvResult_SelectionChanged);

A lot of changes can happen by playing with the properties in the form editor, but let's move on to the meat of the project, cranking out our own lines of code.

Using a StreamReader to count the lines in a file

Reading a file from the system is very easy in C#. The key objects involved are File and StreamReader. The static method File.OpenText opens a file specified by a local or fully-qualified path name, and generates a StreamReader object to digest the file contents. StreamReader is built with the ReadLine method; perfect for our task.

private int CountLinesInFile(string filename)
    StreamReader sr = File.OpenText(filename);
    int count = 0;
    while (sr.ReadLine() != null)
    return count;

Finding Files in a Directory

Our next task is to determine which files we should open. We will make use of the System.Collections.Generic.List<> class to contain our filenames. The following code snippet demonstrates how we collect all the filenames that match the requested extensions:

private void CountFiles()
    // Repository for discovered filenames 
    List<string> filenames = new List<string>();

    // Running linecount total
    int total = 0;

    // The Split method is a quick and dirty way to parse a string.
    string[] extensions = txtExts.Text.Split(" ".ToCharArray());

    foreach (string ext in extensions)
      // The third parameter of this overload allows us to 
      // automatically inspect subdirectories. Default is 
      // SearchOption.TopDirectoryOnly, and the argument 
      // could have been omitted, but is included here for
      // information's sake.
        chkSubDir.Checked ?
            "*." + ext,
            SearchOption.AllDirectories) :
            "*." + ext,

    // ...

Our next task is to open each file, count the lines, and add the results to the DataGridView. We will use the DataGridView.Rows.Add(object[] params) method to add each new row. With this method, each object should correspond, in order, to the columns of the DataGridView.

    // ...

    // Wipe out any previous results

    // No that we have all the filenames, 
    // open the files to count their lines.
    foreach (string filename in filenames)
      int count = CountLinesInFile(filename);
      total += count;

      // This line adds a new row to the DataGridView.
      // We choose the string.Substring method to display
      // only the relative path of the file

    // Add the total to the bottom
       new object[] { "Total:", total.ToString() });

Call this method from the goButton_Clicked event handler, and we have a line counter!

Using MultiSelect with the DataGridView

To wrap things up, we will add functionality to ignore some of the results, if we wish, in our total. The following code snippet counts the results in the selected rows, and writes the results to the StatusStrip below:

private void CountSelection()
    int selected = 0;
    int total = 0;
    foreach (DataGridViewRow row in dgvResult.Rows)
            // Ignore rows that are either not selected 
            // or are the total row. Because some "filler"
            // rows exist, use the catch block to effectively
            // ignore the invalid data in those rows.
            if (row.Selected &&
                row.Cells[0].Value.ToString() != "Total:")
              total += int.Parse(row.Cells[1].Value.ToString());
        catch { }

    // Update the status label with the results
    lblFileCt.Text = selected.ToString() + " files selected";
    lblLineCt.Text = total == 0 ? "No lines" : total.ToString() + " lines";


This article just scratches the surface of file IO and data controls like the DataGridView. I hope you found this article useful. This article is updated and maintained on the author's website at Your feedback is welcome. Thank you for reading.


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Keith Rimington
Web Developer
United States United States
Keith writes ASP.NET 2.0 applications for ATK Launch Systems and researches multi-agent systems with Utah State University.

He maintains his own website, and works to build the skillset necessary to launch a new business, Kbrimington Productions.

Keith lives in Utah with his wife, Delores.

You may also be interested in...

Comments and Discussions

GeneralDatagridView display Pin
rozhanin2-Sep-07 22:07
memberrozhanin2-Sep-07 22:07 
GeneralRe: DatagridView display Pin
Keith Rimington26-Jul-08 19:17
memberKeith Rimington26-Jul-08 19:17 
GeneralRe: DatagridView display Pin
rozhanin27-Jul-08 7:23
memberrozhanin27-Jul-08 7:23 
Generalauthor's website Pin
andre1234513-Jun-07 1:53
memberandre1234513-Jun-07 1:53 
AnswerRe: author's website Pin
Keith Rimington26-Jul-08 19:15
memberKeith Rimington26-Jul-08 19:15 not working Pin
Ed.Poore13-Jul-06 2:09
memberEd.Poore13-Jul-06 2:09 
GeneralRe: not working Pin
Keith Rimington13-Jul-06 16:42
memberKeith Rimington13-Jul-06 16:42 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.151126.1 | Last Updated 27 Jul 2008
Article Copyright 2006 by Keith Rimington
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid