ASP.NET

Read CSV Files in ASP.NET With GridView Display

Comma-separated values files remain one of the most common formats for data exchange. Whether you're importing product catalogs, customer lists, or transaction records, CSV files offer simplicity that many systems still rely on. When building ASP.NET Web Forms applications, you will eventually need to handle CSV imports, and the platform provides everything you need out of the box.

This guide walks through building a complete CSV reader using the FileUpload control, string parsing, and the GridView display component. No third-party libraries required.

At a glance

  • ASP.NET FileUpload control handles CSV file selection and upload
  • String.Split() parses comma-separated lines into arrays
  • DataTable structures parsed rows for binding
  • GridView displays tabular data with built-in sorting and paging
  • Proper encoding and validation are essential for production use
  • CSV libraries handle edge cases better than manual parsing

Setting Up the Upload Interface

Begin by creating a new Web Forms page in Visual Studio. Add three controls to the form: a FileUpload instance for selecting files, a Button to trigger processing, and a GridView to display the imported data.

Style these elements with CSS to make the interface presentable. A simple table border, header background color, and button styling go a long way toward making the import feel polished. The example CSS from the reference uses a pink header and blue button—functional choices that create clear visual hierarchy.

The markup lives in your .aspx file while the processing logic goes in the code-behind. Keep the two concerns separate for maintainability.

Processing the Upload

When the button click event fires, check that a file was actually selected by testing FileUpload.HasFile. Skip processing entirely if no file exists.

Read the uploaded file directly from FileUpload.PostedFile.InputStream without saving it to disk first. This approach keeps temporary files off the server and simplifies cleanup.

StreamReader works well for this, reading the entire file into memory as a string. For large files, consider reading line-by-line to avoid memory pressure.

Parsing CSV Content

The core parsing logic splits each line on commas. A string array captures the column values, which then populate a DataRow.

The first line typically contains headers. Parse it separately to define DataTable columns, then iterate through remaining lines as data rows. The DataTable accepts these rows and provides the binding interface GridView expects.

This manual approach handles straightforward CSV files cleanly. Complications arise when fields contain commas themselves, requiring quoted delimiters, or when line endings vary across systems. The basic String.Split() technique suffices for well-formed exports from tools like Excel.

Displaying Results

Assign the populated DataTable to GridView.DataSource and call DataBind(). ASP.NET renders the table automatically, respecting any styles defined in markup or CSS.

Enable sorting and paging through GridView properties if your use case benefits from them. These features require minimal configuration and add significant usability for larger imports.

Our analysis

The manual parsing approach works best for controlled environments—internal tools, admin panels, or development prototypes. When users submit CSV files from unknown sources, quote handling and encoding variations introduce bugs.

For production systems processing untrusted uploads, established CSV libraries handle these edge cases comprehensively. Libraries like CsvHelper respect RFC 4180 standards and manage quoted fields, escaped characters, and mixed line endings reliably.

That said, building the manual version teaches fundamentals. Understanding streams, string manipulation, and data binding makes you more effective when debugging library behavior or building custom file processing pipelines.

The pattern—upload, preview, confirm—covers most real-world batch import workflows. Users want to see what they're about to import before committing changes.

Practical example

Say you are building an admin tool for importing product catalogs from supplier CSV exports. Suppliers send weekly files with new items, price changes, and discontinued products. The import page displays a FileUpload and preview GridView. After upload, administrators review the parsed rows, correct any obvious errors, then click a confirmation button to execute database updates. This three-step workflow—select, preview, commit—appears across inventory systems, CRM batch imports, and financial data uploads.

Key takeaways

  • Always validate file uploads—check HasFile and restrict allowed extensions
  • Handle character encoding explicitly using System.Text.Encoding.UTF8 or detect from file BOM
  • For production CSV processing with untrusted input, use a dedicated parsing library
  • Enable GridView sorting and paging for larger datasets to improve usability

Frequently asked questions

How do I handle CSV files with quoted fields containing commas?

Basic String.Split() fails with quoted commas. Use TextFieldParser from Microsoft.VisualBasic.FileIO or a dedicated CSV library that respects RFC 4180 formatting rules for production use.

Can I limit the file upload size?

Configure maxRequestLength in web.config's httpRuntime section. The default is 4MB; adjust based on your needs while considering security implications.

How do I export DataTable to CSV instead of importing?

Iterate through DataTable rows, concatenate column values with commas, and write to Response with text/csv content type to trigger browser download.

What encoding should I use when reading CSV files?

Default encoding varies by system. Explicitly specify UTF8 or detect encoding from the byte order mark (BOM) at the file start to handle international characters correctly.

Can I use this approach with ASP.NET Core instead of Web Forms?

The concepts transfer but the controls differ. ASP.NET Core uses IFormFile for uploads and different data binding patterns. The CSV parsing logic remains similar.

Related