CSV file contains Comma Separated Values in plain text format. For an example, refer the below screenshot:

To understand this functionality first we will read CSV file by using DataTable and then we will display csv file data in gridview.
In Your design Page:(Webform.aspx) We will add a FileUpload control, a gridview control
and a button Control.Using FileUpload Control we will select Csv file then we will click on upload button to display the data in gridview.
Include the following code in design part:
<head runat="server">
<title>ReadCsvFile</title>
</head>
<body>
<form id="form1" runat="server">
<div style="color: black;">
<h4>
Read CSV File and display the data in a GridView
</h4>
<asp:GridView ID="CsvGridView" runat="server" CellPadding="4" ForeColor="#333333" GridLines="None">
<AlternatingRowStyle BackColor="White" />
<EditRowStyle BackColor="#7C6F57" />
<FooterStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#BC005A" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#666666" ForeColor="White" HorizontalAlign="Center" />
<RowStyle BackColor="#E3EAEB" />
<SelectedRowStyle BackColor="#C5BBAF" Font-Bold="True" ForeColor="#333333" />
<SortedAscendingCellStyle BackColor="#F8FAFA" />
<SortedAscendingHeaderStyle BackColor="#246B61" />
<SortedDescendingCellStyle BackColor="#D4DFE1" />
<SortedDescendingHeaderStyle BackColor="#15524A" />
</asp:GridView>
<br />
<br />
<table>
<tr>
<td>
Please Select Your Csv File
</td>
<td>
<asp:FileUpload ID="CsvFileUpload" runat="server" />
</td>
<td>
</td>
<td>
<asp:Button ID="CsvButton" runat="server" Text="Upload" OnClick="UploadCsvFile" />
</td>
</tr>
</table>
</div>
</form>
</body>

In Code behind file(Webform.aspx.cs):
1. First Include the following code on button click event:
protected void UploadCsvFile(object sender, EventArgs e)
{
DataTable csvtbl = new DataTable();
csvtbl.Columns.Add("Name");
csvtbl.Columns.Add("EmailId");
csvtbl.Columns.Add("Department");
csvtbl.Columns.Add("Designation");
string GetCsvFilePath = Path.GetFullPath(CsvFileUpload.PostedFile.FileName);
string ReadCSVFile = File.ReadAllText(GetCsvFilePath);
foreach (string CsvFileRow in ReadCSVFile.Split('\n'))
{
if (!string.IsNullOrEmpty(CsvFileRow))
{
csvtbl.Rows.Add();
int count = 0;
foreach (string CsvFileRec in CsvFileRow.Split(','))
{
csvtbl.Rows[csvtbl.Rows.Count - 1][count] = CsvFileRec;
count++;
}
}
//Call BindgridCsv Function
BindgridCsv(csvtbl);
}
}
2. We create a function to display CSV file data in gridview and call the Function inside button click event as we have shown you above:
private void BindgridCsv(DataTable dtcsv)
{
CsvGridView.DataSource = dtcsv;
CsvGridView.DataBind();
}
Please have a look on screenshot:

0 Comment(s)