Link to home
Avatar of anusdesai
anusdesai

asked on

Reading a text file with start and length given

Hi,

I have file
aa bbb ccc
the user enter start position and the length
like start :1
length:2

the output sould be aa

start :3
length:3

the output should be bbb

Its a text file.How do i read it and populate the datagridview with it?

Avatar of Bob Learned
Bob Learned
Flag of United States of America image

VB.NET example:

1) Read the file text
Imports System.IO

...

Dim text As String = File.ReadAllText(filePath)

2) Why would you want to display text in a DataGridView and not a TextBox?

Bob
Avatar of anusdesai
anusdesai

ASKER

Hi,

I have to use :
mid(10,15,str)
where 10 is start position and 15 is the width...
I want to display in datagridview as I have to get columns in the text file depending on the start position
example:

aa bb ccc

data in datagridview

col1   col2   col3
aa      bb       ccc

can u suggest anything?
use substring...

str.substring(10,15)
Hi,
Can you suggest how do I use a streamreader to that..

...assuming all the rows have the same number of columns...

Here is one way:

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim contents As String = My.Computer.FileSystem.ReadAllText("c:\someFile.txt")

        Dim ds As New DataSet
        Dim tb As DataTable = ds.Tables.Add("MyTable")

        Dim values() As String
        For Each row As String In contents.TrimEnd(New Char() {vbCr, vbLf}).Replace(vbCrLf, vbCr).Split(vbCr)
            values = row.Split(" ")
            If tb.Columns.Count = 0 Then
                For i As Integer = 1 To values.Length
                    tb.Columns.Add("Column " & i)
                Next
            End If
            tb.Rows.Add(values)
        Next

        DataGridView1.DataSource = tb
    End Sub
Hi,

Will try and get back...

Regards.
Thanks, Mike, you old hound dog :D

Bob
=)

There very well might be a faster way though!

I don't play with DataSets/DataGridViews very much...
Hi,

But ,its not using
str.substring(10,15)
defined by the user..
and also i get an error that input array is larger than the number of columns

Regards.
The code I gave takes a text file and populates a datagridview with the data from it (assuming all the rows in the text file have the same number of columns).

"defined by the user.."

Can you give us a bigger picture here please?....
Look at the Microsoft.VisualBasic.FileIO.TextFieldParser with 2005.

Bob
If you want to manually build each DataRow using specific pieces of the text from the lines in the file then do something LIKE:

*** there are many ways to do this...more info might be helpful ***

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim contents As String = My.Computer.FileSystem.ReadAllText("c:\someFile.txt")

        Dim ds As New DataSet
        Dim tb As DataTable = ds.Tables.Add("MyTable")

        For i As Integer = 1 To 3
            tb.Columns.Add("Column " & i)
        Next

        Dim values As ArrayList
        For Each row As String In contents.TrimEnd(New Char() {vbCr, vbLf}).Replace(vbCrLf, vbCr).Split(vbCr)            
            values = New ArrayList
            values.Add(row.Substring(0, 2))
            values.Add(row.Substring(3, 3))
            values.Add(row.Substring(7, 3))
            tb.Rows.Add(values.ToArray)
        Next

        DataGridView1.DataSource = tb
    End Sub
Hi,

My requirement

Example
text file:

aa  bb ccc

In this the user inputs the start row and length and the column name for datagridview

on this basis

I populate a datagridview


aa  cc  or
aa bb cc ...depending on what inputs are from the user.

Now the columns here will be from the table the user selects.
Suppose table a has col1 col2 col3 then datagridview has columns:

col1 col2 col3

the user  inputs the column names when he inputs the start and length
example:                    column for datagridview    startpositioni.e 1     length i.e.2

here in our case            col1                                          1                     2

i have to retrieve        aa  and populate datagridview like this:

col1    col2                            col3

aa        bb (e.g same as aa)        cc (e.g same as aa)      -------



 


Regards.


You were given a pretty good example of reading a text file and breaking the strings up by index, so where don't you understand?
ASKER CERTIFIED SOLUTION
Avatar of Sancler
Sancler

Blurred text
THIS SOLUTION IS ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
Hi Sancler,
Excellant code...
Well,thanks to  Idle_Mind too...

Regards.
Hi,
I get this error in this case
 values.Add(row.Substring(43, 5))
or start position is 43 and length is 5

error:
startIndex cannot be larger than length of string.
Parameter name: startIndex

Hi experts,

Hi,
I get this error in this case
 values.Add(row.Substring(43, 5))
or start position is 43 and length is 5

error:
startIndex cannot be larger than length of string.
Parameter name: startIndex

Please help its urgent!!!!
The settings that the user enters have to be consistent with the length of the lines/rows in the text file.  Assuming that the 43 comes from a user entry, in this case they are not.  That error message means that the line/row that is being read does not have at least 44 characters in it: 44 because the index is zero-based.

If there is a possibility of this sort of thing happening (and it seems that there obviously is) you will (a) need to introduce some checks to see when it is happening and (b) decide what the program should do when it does happen.

Roger
Hi,

This is one line of a fixed width file:
User will use textpad for finding the position

12345678   dgf gfgggg                    fffgg                                  Mrs   fgfghhhhhh    Orange Farm Cottages        Cammeringham Cliff            Lincoln                                 LN1  2YH                YE810743D  21111994         Dkk   0                  00378372    jhh               30-95-0525032005   110055920242100   Full Time     01052005              4412         0      3500          28052005     8823328052005     91733     58932805200525032005 3850 3850  41688312B242A           Y


and the user gives :

start                                       length
1                                               8             output 12345678  
11(on textpad )                         10                         dgf gfgggg
43    (on textpad )                    5                       fffgg ------this is expected and igetting error here.


Roger,I am not allowed to change this.
With this information I have to populate my Datagridview.

Regards.


                                           
You will have to debug this yourself.  You know precisely what code you're using, we don't.  You know precisely what your data is, we don't.  It's not possible from your post to work out, at a distance, what is going wrong.  For instance, if I copy and paste the example data above into NotePad I get fffgg starting at position 42 counting the first position as 1 or 41 with a zero-based index.  I am not saying I am right and you are wrong.  Just illustrating that this is not the sort of thing that anyone else can do for you via posts in EE.

You need to put some (temporary) debugging print-outs, or put a break point in the code and inspect what is in the variables, so that you can see why what looks like a much longer line than 44 characters is being treated by the code as having less than 44 characters.  So, for instance, assuming you are using the code above, put

   Debug.WriteLine(row)

between

        For Each row As String In contents.TrimEnd(New Char() {vbCr, vbLf}).Replace(vbCrLf, vbCr).Split(vbCr)

and

            values = New ArrayList

to see whether the "row" which is being produced by that code is precisely the line that you are seeing in "textpad".  Once you have that sort of information we might be able to suggest where else to direct debugging efforts.  But they will still be efforts you have to make yourself.

Roger
Hi,
Fine will work it out ....and get back...

Cheers

Hi,

I managed to read the values by this function:
 Using reader As IO.StreamReader = File.OpenText(frmmain.txtinp.Text)
                    '  
                    Dim Line As String
                    Do
                        Line = reader.ReadLine
                       
                        For g As Integer = 0 To frmmain.DataGridView2.Rows.Count - 1
                            arrcurrentrow.Clear()
                            startfield = frmmain.DataGridView2.Item(2, g).Value
                            lengthfield = frmmain.DataGridView2.Item(1, g).Value
                                                    MsgBox(Mid(Line, startfield, lengthfield))
                            currentRow = (Mid(Line, startfield, lengthfield))
                            arrcurrentrow.Add(currentRow)                                                                  

                        Next
   Loop Until Line Is Nothing
can you suggest on how can i get datarows for a datagridview from these values


Example:
col1                                   col2                      col3                
1                                            8                      12345678  
11                                         10                       dgf gfgggg
43                                           5                       fffgg


Right now the output is like   1
                                              8
                                               12345678  
 Loop Until Line Is Nothing
then start position i.e   Line = reader.ReadLine

output is like                         11
                                             10      
                                             dgf gfgggg

                                but,not sure how to get datarows in the above format(Example)

Regards.






You've already got a suggestion of how to do that.  It's this code

        Dim values As ArrayList
        For Each row As String In contents.TrimEnd(New Char() {vbCr, vbLf}).Replace(vbCrLf, vbCr).Split(vbCr)
            values = New ArrayList
            For Each dr As DataRow In tblDetails.Rows
                values.Add(row.Substring(dr("Start"), dr("Length")))
            Next
            tblMain.Rows.Add(values.ToArray)
        Next
        dgvMain.DataSource = tblMain

That you may have changed (a) the method of reading from My.Computer.FileSystem.ReadAllText to a StreamReader (b) the method of getting lines from reading all the text and splitting it to reading line by line (c) the source of the start and length values from a datatable to a dataview (d) the names of some of the variables and (e) some other bits and pieces does not require any alteration to the method in that of handling the output.  You add each result to the arraylist, you create a datatable's row with those values, converting the ArrayList to an Array, and you bind the datagridview to the datatable.

What is the problem with that?

Roger
Cheers.
You're so polite and patient Roger....   =)

Mike

I try to be.  It's good to know I appear to succeed.

Roger
Hi  Sancler,

Thanks for the help..... code is working perfect.....


Regards.