• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 667
  • Last Modified:

VB.NET Read from text file located on website and insert into DataGridView1

Hi I have to read a text file line by line and insert values into DataGridView1
Note: Text file is located on my website http://mywebsite.com/textfiletoread.txt

text file content:
12.24.2009 12:38am  127.0.0.1 file.exe
table.png
0
_ColdFire_
Asked:
_ColdFire_
  • 10
  • 5
1 Solution
 
Muhammad Ousama GhazaliSolution Analyst & ArchitectCommented:
Please see if the attached code helps you for your requirements:
 

' Assuming dgvTemp is the name of the DataGridView control
Dim dtData As New DataTable("NetworkFiles")
Dim row As DataRow = Nothing

With dtData.Columns

	.Add("Date", System.Type.GetType("System.DateTime"))
	.Add("Time", System.Type.GetType("System.DateTime"))
	.Add("IpAddress", System.Type.GetType("System.String"))
	.Add("File", System.Type.GetType("System.String"))

End With

Dim strUrl As String = "http://mywebsite.com/textfiletoread.txt"
Dim httpRequest As HttpWebRequest = WebRequest.Create(strUrl)
Dim httpResponse As HttpWebResponse = CType(httpRequest.GetResponse(), HttpWebResponse)

If httpResponse.StatusCode = HttpStatusCode.OK Then

	Dim responseLength As Integer = httpResponse.ContentLength

	If responseLength > 0 Then

		Dim readStream As New StreamReader(httpResponse.GetResponseStream())
		Dim strLine As String

		While (strLine = readStream.ReadLine()) <> Nothing

			' assuming the line has various elements delimeted by a comma
			Dim strValues() As String = strLine.Split(","c)

			row = dtData.NewRow()
			' Set the dispaly format of the datagridview to display only date part
			row("Date") = CType(strValues(0), DateTime)
			' Set the dispaly format of the datagridview to display only time part
			row("Time") = CType(strValues(1), DateTime)
			row("IpAddress") = strValues(2)
			row("File") = strValues(3)

			dtData.Rows.Add(row)

			row = Nothing

		End While

		readStream.Close()
		readStream = Nothing

		If dtData.Rows.Count = 0 Then
			MessageBox.Show("No records could be found.")

		Else
			Dim dgvTemp As New DataGridView()
			dgvTemp.DataSource = dtData

		End If

	Else
		MessageBox.Show("No records could be found.")

	End If

Else
	MessageBox.Show("An error occured while retreiving values from web server.")

End If

Open in new window

0
 
_ColdFire_Author Commented:
With dtData.Columns

        .Add("Date", System.Type.GetType("System.DateTime"))
        .Add("Time", System.Type.GetType("System.DateTime"))
        .Add("IpAddress", System.Type.GetType("System.String"))
        .Add("File", System.Type.GetType("System.String"))

End With

All this should be read from FILE.. there is a text file where is already date time ip and file info just have to read it line by line and insert into table.
0
 
_ColdFire_Author Commented:
Look at the new file :P Everything is explained there
Like-it-should-be.png
0
Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

 
Muhammad Ousama GhazaliSolution Analyst & ArchitectCommented:
I'm not disrespectful but I think you need to understand the columns and rows of a table and also that how Data Controls work in .NET and/or ASP.NET.
1. The code you referred in your first response is adding just plain columns (structure to a DataTable. Consider it as adding headers to your DataTable object which will then be bound to DataGridView. It is not adding any data/rows to the DataTable.
2. The data available in text file cannot be directly mapped to a DataGridView easily. You have to read that data first into an object such as DataTable that can be used as a binding data source of the DataGridView.
3. Change Line 30 of the above code provided to either of the following if there is a single space or tab between various values of a single line:
Dim strValues() As String = strLine.Split(" "c)
Or
Dim strValues() As String = strLine.Split(vbTab)
4. Please go through the code and try to understand it by executing/debuggin it and also looking into the MSDN (local or online) for further help on any of the part of the code.  
0
 
_ColdFire_Author Commented:
Always saying   No records could be found
0
 
_ColdFire_Author Commented:
Also: Warning      1      Variable 'strLine' is used before it has been assigned a value. A null reference exception could result at runtime.      Form1.vb      33      24
0
 
Muhammad Ousama GhazaliSolution Analyst & ArchitectCommented:
1. Please debug the code and see if the code does go within the While loop starting on Line 27. Further check on Line 30 you have single line of text available to you within the variable name strLine. If yes, try to find out what is the exact delimeter (separator of values on a single line) and use that to split the string.
2. I'll come back to you on how to fix that warning because its important but let's resolve our primary issue first.
I'll again recommend you to understand the code elements and logic to better grasp what you wish to acheive. Further, the code provided assumes that you have set the DataGridView with 4 columns in design time or runtime before executing the provided code.
0
 
_ColdFire_Author Commented:
This is what I have now..
Imports System.IO
Imports System.Net

Public Class Form1
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        ' Assuming dgvTemp is the name of the DataGridView control
        Dim dtData As New DataTable("NetworkFiles")
        Dim row As DataRow = Nothing

        With dtData.Columns

            .Add("Used_On", System.Type.GetType("System.String"))
            .Add("Time", System.Type.GetType("System.String"))
            .Add("IpAddress", System.Type.GetType("System.String"))
            .Add("File", System.Type.GetType("System.String"))

        End With

        Dim strUrl As String = "http://downloads.e3mc.net/f.txt"
        Dim httpRequest As HttpWebRequest = WebRequest.Create(strUrl)
        Dim httpResponse As HttpWebResponse = CType(httpRequest.GetResponse(), HttpWebResponse)

        If httpResponse.StatusCode = HttpStatusCode.OK Then

            Dim responseLength As Integer = httpResponse.ContentLength

            If responseLength > 0 Then

                Dim readStream As New StreamReader(httpResponse.GetResponseStream())
                Dim strLine As String

                While (strLine = readStream.ReadLine()) <> Nothing

                    ' assuming the line has various elements delimeted by a comma
                    Dim strValues() As String = strLine.Split(" "c)

                    row = dtData.NewRow()
                    ' Set the dispaly format of the datagridview to display only date part
                    row("Used_On") = CType(strValues(0), DateTime)
                    ' Set the dispaly format of the datagridview to display only time part
                    row("Time") = CType(strValues(1), DateTime)
                    row("IpAddress") = strValues(2)
                    row("File") = strValues(3)

                    dtData.Rows.Add(row)

                    row = Nothing

                End While

                readStream.Close()
                readStream = Nothing

                If dtData.Rows.Count = 0 Then
                    MessageBox.Show("No records could be found.")

                Else
                    Dim dgvTemp As New DataGridView()
                    dgvTemp.DataSource = dtData

                End If

            Else
                MessageBox.Show("No records could be found.")

            End If

        Else
            MessageBox.Show("An error occured while retreiving values from web server.")

        End If
    End Sub

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

    End Sub
End Class

Open in new window

IMAGE1.png
0
 
_ColdFire_Author Commented:
http://downloads.e3mc.net/f.txt     this is the text file, everything is separated by space.
0
 
_ColdFire_Author Commented:
       With dtData.Columns

            .Add("Used_On", System.Type.GetType("System.DateTime"))
            .Add("Time", System.Type.GetType("System.DateTime"))
            .Add("IpAddress", System.Type.GetType("System.String"))
            .Add("File", System.Type.GetType("System.String"))

        End With

like this also not working..
0
 
Muhammad Ousama GhazaliSolution Analyst & ArchitectCommented:
Sorry, but right now I don't have access to Visual Studio. Will come back to you tomorrow morning.
In the meantime, I'll just recommend confirming that on Line 19 while in debug mode that dtData.Columns.Count is 4 or not. If yes, then see if Line 20 or 21 is not producing an exception and try to go line by line in debug mode to track the problem. Use the Immediate Window or IDE-based accelerated object-explorer (works when you hover mouse on an object/variable name in IDE) while in debug mode.
0
 
_ColdFire_Author Commented:
It might sound kinda retarded but I don't know how to debug line by line :D
0
 
_ColdFire_Author Commented:
ok, w8thing.
0
 
Muhammad Ousama GhazaliSolution Analyst & ArchitectCommented:
Please carefully read the following code and try to do as guided.

' Assuming dgvTemp is the name of the DataGridView control
' And four unbound columns have been created in the above control as follows:
' Column 1- Name: LogDate; DataPropertyName: LogDate; Header Text: Log Date; ReadOnly: True
' Column 2- Name: LogTime; DataPropertyName: LogTime; Header Text: Log Time; ReadOnly: True
' Column 3- Name: IpAddress; DataPropertyName: IpAddress; Header Text: IP Address; ReadOnly: True
' Column 4- Name: File; DataPropertyName: File; Header Text: File; ReadOnly: True

Dim dtData As DataTable = Nothing
Dim row As DataRow = Nothing

Try
	dtData = New DataTable("LogFiles")

	With dtData.Columns

		.Add("LogDate", System.Type.GetType("System.String"))
		.Add("LogTime", System.Type.GetType("System.String"))
		.Add("IpAddress", System.Type.GetType("System.String"))
		.Add("File", System.Type.GetType("System.String"))

	End With

	Dim strUrl As String = "http://downloads.e3mc.net/f.txt"
	Dim httpRequest As HttpWebRequest = WebRequest.Create(strUrl)
	Dim httpResponse As HttpWebResponse = CType(httpRequest.GetResponse(), HttpWebResponse)

	If httpResponse.StatusCode = HttpStatusCode.OK Then

		Dim responseLength As Integer = httpResponse.ContentLength

		If responseLength > 0 Then

			Dim readStream As New StreamReader(httpResponse.GetResponseStream())
			Dim strLine As String = String.Empty

			While True

				strLine = readStream.ReadLine()

				If strLine Is Nothing OrElse strLine.Equals(String.Empty) Then Exit While

				Dim strValues() As String = strLine.Split(" "c)

				row = dtData.NewRow()

				row("LogDate") = strValues(0)
				row("LogTime") = strValues(1)
				row("IpAddress") = strValues(2)
				row("File") = strValues(3)

				dtData.Rows.Add(row)

			End While

			readStream.Close()
			readStream = Nothing

			If dtData.Rows.Count = 0 Then
				MessageBox.Show("No records could be found.")

			Else
				dgvTemp.AutoGenerateColumns = False
				dgvTemp.DataSource = dtData

			End If

		Else
			MessageBox.Show("No records could be found.")

		End If

	Else
		MessageBox.Show("An error occured while retreiving values from web server.")

	End If

Catch ex As Exception
	MessageBox.Show("An unexpected error occured while loading data. The details are: " & vbCrLf & ex.ToString())

Finally
	dtData = Nothing
	row = Nothing

End Try

Open in new window

0
 
_ColdFire_Author Commented:
That worked. Thank you.
0

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

  • 10
  • 5
Tackle projects and never again get stuck behind a technical roadblock.
Join Now