Please Help me in converting VB6 DataGrid usage to VB2005 DataGridView.
Hi,
I am a newbie VB6 programmer looking for assistance in converting the following code into VB2005 code. No matter what I seem to do I cannot get an equivalent that will run using VB2005.
I have to stay with the existing file format due to legacy issues. I would like to read and write randomly as shown. I'm also confused on how to get the data into the VB2005 DataGridView.
Any help would be greatly appreciated. Thanks PaulZ
A snippet of my VB6 code -
Private Type DiskFileLayout
dAccount As Integer
dActivity As String * 10
dCurrency As Integer
dDate As Date
dTotal As Currency
dContainers As Double
dPrice As Currency
dCommission As Currency
dNote As String * 33
dLotNumber As Integer
dActive As String * 1
dLotCnt As Integer
dLotSeries(1 To 18) As Integer
End Type
Dim dNFile As DiskFileLayout
Private Sub ReadData()
Open "C:\ShipmentData" For Random As #1
Get #1, , dNFile
MSFlexGrid1.TextMatrix(1, 6) = Format(dNFile.dTotal, "$#,###,##0.0000") & " " 'total
[2766 byte] By [
Paulyz] at [2007-12-24]
The changes between ADO classic and ADO .Net are great and varied. There's quite a mind-set change to the way you access and display data; and about the only way to get there is to read up on ADO.
Now, in this particular case, it looks like you're loading a flat text file to get your data. You'll probably want to create a new DataSet in the project that contains a table with the "DiskFileLayout" for it's schema. Then you'll need to read and parse the text file into the dataset (there are posts about how this can be done - search for "text data provider"). Finally you'll bind the DataSet to a BindingSource and the BindingSource to the DataGridView.
The DataGridView will be used for GUI edits of the data; any programatic edits you do should be done through the BindingSource to affect the currently selected record, or to the DataSet itself for changes unrelated to the current position in the table.
There are lots of examples out there. The search mentioned above should yeild code for going to/from and DataSet/Text File. Searching for "ADO", "DataSet", and "BindingSource" should also yeild useful results.
GL.
Although I did not use the structure to read the value I did show you what was neccessary to convert it, along with some other items to give you an idea of what is going on...try something along these lines here:
Private Structure DiskFileLayout
Public dAccount As IntegerPublic dActivity As Char()Public dCurrency As IntegerPublic dDate As DatePublic dTotal As DecimalPublic dContainers As DoublePublic dPrice As DecimalPublic dCommission As DecimalPublic dNote As Char()Public dLotNumber As IntegerPublic dActive As CharPublic dLotCnt As IntegerPublic dLotSeries() As IntegerEnd StructurePrivate Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.ClickDim dNFile As DiskFileLayoutReDim dNFile.dActivity(10)ReDim dNFile.dNote(33)ReDim dNFile.dNote(1)ReDim dNFile.dLotSeries(17)Dim SizeOfInteger As Integer = System.Runtime.InteropServices.Marshal.SizeOf(GetType(Integer))Dim SizeOfChar As Integer = System.Runtime.InteropServices.Marshal.SizeOf(GetType(Char))Dim SizeOfDate As Integer = System.Runtime.InteropServices.Marshal.SizeOf(GetType(Date))Dim SizeOfDec As Integer = System.Runtime.InteropServices.Marshal.SizeOf(GetType(Decimal))Dim SizeOfDouble As Integer = System.Runtime.InteropServices.Marshal.SizeOf(GetType(Double))Dim BufferSize As Integer = System.Runtime.InteropServices.Marshal.SizeOf(dNFile)Dim TheBuffer(SizeOfDec) As ByteDim TheOffset As Integer = (SizeOfInteger * 2) + (SizeOfChar * 10) + SizeOfDateDim fr As New System.IO.FileStream("C:\ShipmentData", IO.FileMode.Open, IO.FileAccess.Read, IO.FileShare.None, BufferSize, IO.FileOptions.RandomAccess)fr.Read(TheBuffer, TheOffset, SizeOfDec)fr.Close()
Dim TheCell As DataGridViewCellMe.DataGridView1.Columns.Add("Col1", "Col1")TheCell = Me.DataGridView1.Rows(0).Cells(0)TheCell.Value = Convert.ToDecimal(TheBuffer)Me.DataGridView1.CurrentCell = TheCellEnd Sub
On the other hand the get and open functions were directly replaced with FileOpen and FileGet...but do read the help files on those functions because the functionallity has changed...stuff will get added to your buffer when using the FileGet function
Hope that helps
GL, Thank you for the response.
I reviewed the "text data provider" posts and I am still confused on how to create the "DiskFileLayout" (schema) table. You are correct that I'm loading a flat text file.
I created the DataSet called "PaulyDataSet.xsd" , then in the Toolbox I dragged the DataTable icon to the "PaulyDataSet.xsd" workspace. I have a box called DataTable1 that I don't know how to use. I have a few VB05 books and the VB05 help but I don't know how to continue.
Can you offer any more code samples or suggest other locations for insights. Thanks PaulyZ
Ok, you're getting there...
You'll want to right-click on that DataTable1 box and select Add -> Column. You add a column to the dataset for each field in your structure. Set the column datatype appropriately (typically you can use String and Int32/Decimal for most types).
Once you've created the DataTable schema (or, column layout) you can then parse the text file and load the values into an instance dataset.
BTW, "GL" is short hand for "Good Luck" 
GL!
-rkimble
-EDIT- More info on column types:
Here are some recomended datatypes for your existing layout:
dAccount As Integer = Int32
dActivity As String * 10 = String
dCurrency As Integer = Int32
dDate As Date = DateTime
dTotal As Currency = Decimal
dContainers As Double = Double
dPrice As Currency = Decimal
dCommission As Currency = Decimal
dNote As String * 33 = String
dLotNumber As Integer = Int32
dActive As String * 1 = Char
dLotCnt As Integer = Int32
dLotSeries(1 To 18) As Integer = ? Not sure about this... looks like you want to add 18 more Int32 columns
Hi Reed,
Ok that's a big help. This is so different...
In my layout I have a field dNote that is a string (length 33) and dLotSeries that represents 18 integers (links to other information if needed). I would assume that the DataTable needs to know there is a length associated with these fields. How does one represent that in the DataTable? I would prefer not to make them individual fields if possible since it would really cream how the data is processed.
Once the DataTable is done how do I go about reading the data from the flat file?
Thanks PaulyZ
The strings you don't have to worry about. You can set the MaxLength property of the column if you want, but its optional (there are other methods of ensuring the user does not enter too long of a string).
The 18 integers I'm not sure about... You're not going to be able to display an Array in the dataset... This would either have to be 18 seperate fields, or a relationship to a second table.
What does your flat file look like? Is it comma seperated values or fixed width? That will determine the routine necessary to load the file into the dataset.
How would making 18 integer columns adversly affect the processing of the file?
Reed,
The file is flat, no CSV's althought there might be embedded comas in the text. The VB6 Type function set the widths of the fields.
The 18 integers could be separate columns if needed.
PaulyZ
OK, add the 18 integer columns to the end of the table.
In the design view of your form, drag a DataGridView, a BindingSource, and your DataSet (be sure to Build the project - this will make the DataSet you created appear in the top of the Toolbox) from the ToolBox onto the form. The DataGridView.DataSource property should be set to the BindingSource. Later, after filling the dataset with data, you'll set the BindingSource.DataSource to the DataSet and the BindingSource.DataMember to the name of the Table.
Then, you'll use code something like the following to do the import:
Dim tfp As new FileIO.TextFieldParser("c:\datafile.txt") 'replace "c:\datafile.txt" with the actual file name & path
tfp.TextFieldType = FileIO.FieldType.FixedWidth
tfp.FieldWidths = New Integer() {1, 10, 1, 8...} 'these integers should be a comma seperated list of all the field widths
tfp.HasFieldsEnclosedInQuotes = True/False 'set this property to true if the field values are enclosed in quotes
While Not tfp.EndOfData
Dim vals() As String = tfp.ReadFields
Dim dr As PaulyDataSet.DataTable1Row 'the type here should be your datasetname dot datatablenamerow
dr = PaulyDataSet1.DataTable1.NewDataTable1Row 'again, the names should match your dataset schema
For i As Integer = 0 To vals.Length - 1
dr.Item(i) = vals(i)
Next
PaulyDataSet1.DataTable1.AddDataTable1Row(dr)
End While
BindingSource1.DataSource = PaulyDataSet1
BindingSource1.DataMember = "DataTable1"
You'll need to make minor adjustments to the code, as noted, but this should give you the basic idea: read the field values into an array, create a new DataRow, set the columns in the DataRow equal to each value read from the file, add the row to DataTable, wash, rinse, repeat.
Hi Reed,
Thanks for the continued wisdom and advice.
I added the above code, did the build (I think I did it right) and then entered the debug. I get the following error:
"Input string was not in a correct format.Couldn't store < > in dAccount Column. Expected type is Int32."
I cannot see any file data and I wonder how I can trace what is happening. How can I tell if its opening the flat file and reading the data?
On my form I have a button to start things, a DataGridView and then the DataTable1 grid (when I dragged the datatable1 onto the form). Seems like the DataTable1 is also a DataGridView so do I need the first one?
Thanks PaulyZ
That error looks like it found a blank value (or space " ") for dAccount in the flat file. You may have to modify the code a little further to test for blank, or null, values. Something like:
For i As Integer = 0 To vals.Length - 1
If vals(i).Trim.Length > 0 Then
dr.Item(i) = vals(i)
End If
Next
It may take more testing than that - it all depends on what that flat file might contain.
As to the controls on your form - It sounds like you drug the DataTable object from the DataSources window onto the form. This would have created a DataGridView and BindingSource for you - each with it's datasource already set. This is ok, you just have to reset the BindingSource.DataSource after filling the DataSet.
So if this is the case then you don't need the other DataGridView control.
Hi Reed,
I'm close to getting the data, but a few more questions.
The code line: "Dim vals() As String = tfp.ReadFields" appears to take all my flat file data and convert it to a string value. That messes up my fields that were Integer, Date, Currency, etc. Is there anyway to do the read preserving the data type of the data? If not, would you suggest I convert it back item by item?
I cleared my design form and went back over the following directions: "In the design view of your form, drag a DataGridView, a BindingSource, and your DataSet (be sure to Build the project - this will make the DataSet you created appear in the top of the Toolbox) from the ToolBox onto the form."
I didn't understand the build project before but got it this time. My DataGridView is grey with no columns or column headings. When I built it incorrectly the prior time I had two DataGridViews on the form one that I dragged over had all the columns and column headings. I'm not sure if the current DataGridView should have columns and column headings that represent the dataset datatypes. Can you tell me if the columns and headings should be there? If not when do they show up?
Thanks PaulyZ
#1 - Don't worry about data types while reading the file.
Because it is a flat text file, the values you're reading are strings. When those values get set in the DataRow, they then get converted to the proper data type based on the DataType property of the specific column in the DataTable.
#2 - How to add Columns to the Grid.
When you did the first drag and drop operation, VS automatically added a column to the DataGridView for each column in the DataTable. You have two choices here: 1, you can manually add the columns to the DataGridView from the properties window; or 2, you can use the code DataGridView1.AutoGenerateColumns = True (where DataGridView1 is the name of your DataGridView). This code would probably be one of the first lines of From_Load.
Keep it up! You're almost there!! 
Hi Reed,
Unfortunately the flat file is not a "Text" file. If you look at the first message I posted you can see the VB6 Type's that were used for the file structure. The only portion that is text is dNotes.
The error that I am getting "Input string was not in a correct format.Couldn't store < > in Account Column. Expected type is Int16." is due to an integer value of zero in the first value in the flat file. There are many more non ascii data values in the files I get.
What do you suggest ?
I figured out how to see the data that's being read positioning the cursor over the "vals()" variable. Pretty cool and different.
Thanks again coach :-)
Sorry, that VB6 stuff means very little to me...
Ok, I guess we've got a terminology conflict. To me, a flat file is always ASCII text. It's either delimited with some characters, or fixed width data file. A flat file is one that can be parsed and should be readable in notepad. Excel will be able to import and display it's contents.
What you're describing now sounds like a binary file. A file that contains byte data, some of which will convert to characters when seen in Notepad, others will display as all kinds of funky characters, or not at all.
If this is a binary file than the method of importing it into a DataSet is different. You'll have to read it into a byte array with the proper encoding and then use a routine that translates groups of bytes into their appropriate values. This is a very different process than reading a flat data file into a dataset...