Hello Firends
As i promise to you i write the two post for the csv import and export data this is the second post which will give you code for the import any csv file in to the gridview.
please check below code which will import any csv file into the asp.net gridview.
first add this code in aspx file
<asp:Label runat=”server” ID=”err_lbl” ForeColor=”Red” />
<asp:FileUpload runat=”server” ID=”FileUpload1″ Height=”20px” />
<asp:CheckBox runat=”server” ID=”first_row_check” Text=”First Row Contains Headers”Checked=”true” />
<asp:Button runat=”server” ID=”Button1″ OnClick=”Upload_File” Text=”Upload & Verify” />
<asp:GridView runat=”server” ID=”GridView1″ Caption=”File Contents” ></asp:GridView>
then write below cod in the aspx.vb file.
Protected Sub Upload_File(ByVal o As Object, ByVal e As EventArgs)
If Not FileUpload1.HasFile Then
err_lbl.Text = “Missing Upload File”
Exit Sub
End If
If Path.GetExtension(FileUpload1.FileName).ToLower() <> “.csv” Then
err_lbl.Text = “Invalid File Type only csv files accepted”
Exit Sub
End If
FileUpload1.SaveAs(Server.MapPath(”temp.csv”))
Dim reader As StreamReader = New StreamReader(Server.MapPath(”temp.csv”))
Try
Dim dt As New DataTable()
Dim colCount As Integer = 0
If first_row_check.Checked = false Then
dt.Columns.Add(”UserNo”)
dt.Columns.Add(”UserName”)
dt.Columns.Add(”UserAddress”)
dt.Columns.Add(”Phone”)
dt.Columns.Add(”Email”)
Else
Dim header As String() = reader.ReadLine().Split(New Char() {”,”c})
If colCount = 0 Then
colCount = header.Length
End If
For Each str As String In header
dt.Columns.Add(str)
Next
End If
Dim err_str As New System.Text.StringBuilder()
Dim row_num As Integer = 0
Dim error1 As Boolean = False
While Not reader.EndOfStream
Dim lineContents As String() = reader.ReadLine().Split(New Char() {”,”c})
If colCount = 0 Then
colCount = lineContents.Length
End If
‘ do some error checking
If colCount <> lineContents.Length Then
err_str.AppendLine(String.Format(”error found on line {0} expected {1} columns found {2}”, row_num.ToString(), colCount.ToString(), lineContents.Length.ToString()))
error1 = True
Else
Dim new_row As DataRow = dt.NewRow()
For i As Integer = 0 To lineContents.Length - 1
new_row(i) = lineContents(i)
Next
dt.Rows.Add(new_row)
End If
row_num += 1
End While
If error1 Then
err_lbl.Text = err_str.ToString()
End If
GridView1.DataSource = dt
GridView1.DataBind()
Catch ex As Exception
err_lbl.Text = ex.Message.ToString()
Finally
reader.Close()
reader.Dispose()
File.Delete(Server.MapPath(”temp.csv”))
End Try
End Sub
Enjoy code.
please comment me on this post if you will find anything wrong in code or you will not executed perfectly i will help you on this code
Hello ! I am Arjun Jadeja a Software Engineer by Profession. You can contribute and I will distribute your ideas through this site. Thanks and Enjoy
Leave a reply